How to find difference between two dates in Java 8? Example Tutorial

One of the most common programming task while working with date and time objects are calculating the difference between dates and finding a number of days, months or years between two dates. You can use the Calendar class in Java to get days, months between two dates. The easiest way to calculate the difference between two dates is by calculating milliseconds between them by converting java.util.Date to milliseconds using the getTime() method. The catch is converting those milliseconds into Days, Months and Year is not tricky due to leap years, the different number of days in months and daylight saving times.

You can also use the TimeUnit class to convert milliseconds into seconds, minutes and other time units.

If you are running in Java 6 or Java 7 and cannot use any third party library then use Calendar class to find the difference, else use the JodaTime library. You have to use Joda in order to calculate the accurate difference, there are no better ways than using JodaTime in the pre-Java 8 world.

If you are running in Java SE 8 then its better to use the new Date and Time API, which is a lot cleaner, readable, and robust than Calendar and old date-time API. In case, you are not familiar with Java 8 features, I suggest you join The Complete Java MasterClass course on Udemy, which not just covered Java 8 features but also new features from the latest Java releases. It's one of the most up-to-date courses out there. 




Using JodaTime to find the difference between two dates in Java

Using JodaTime, you can get the difference between two dates in Java using the following code:

Days d = Days.daysBetween(startDate, endDate).getDays();

And, if you want to find the difference between two dates in Java in Months, then you can use the following code example:

Months m = Days.daysBetween(startDate, endDate).getMonths();

And, if you want to calculate the difference between two dates in Java in Years, here is the code you need to use:

Months m = Days.daysBetween(startDate, endDate).getYears();

Similarly, you can calculate the difference between two dates in Java in Weeks by changing getYears() method to getWeeks() as shown below:

Months m = Days.daysBetween(startDate, endDate).getWeeks();

And, finally, if you want to get the difference between two dates in Java in Hours then you can use getHours() method as shown in the following example:

Months m = Days.daysBetween(startDate, endDate).getWeeks();

You can calculate the difference between two dates in months by using the Calendar class and if you need code you can check this example, but honestly, I don't recommend it until it is the only way for you. If you only care about absolute difference then this solution works. You can also do the same using the Joda Time library and by using the new Date and Time API of Java 8.

Btw, if you want to learn more about Java APIs in-depth, I also suggest you check out The Complete Java MasterClass course on Udemy, which not just covered Java 8 features but also new features from the latest Java releases. It's one of the most up-to-date courses out there. 

How to find difference between two dates in Java?


Solution 2: Using Java 8 Date and Time API

This is the best way to find difference between two dates in Java as its very clear and readable and you don't need to use any external library.  Here is the sample code example to find a number of days, months and years between two dates in Java.

Btw, there is a lot to learn about Date and Time API of Java 8, and you are interested, I suggest you check out What's New in Java 8 course on Pluralsight, which covers Java 8 features and will teach you everything you need to know about Java 8 in a very short time. 

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

/**
 * Java Program to calculate number of years and months
 */
public class Java8Demo {

    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        LocalDate bday = LocalDate.of(1955, Month.MAY, 19);
        LocalDate today = LocalDate.now();
        
        Period age = Period.between(bday, today);
        int years = age.getYears();
        int months = age.getMonths();
        int days = age.getDays();
        
        System.out.println("number of days: " + days);       
        System.out.println("number of years: " + years);
        System.out.println("number of months: " + months);
    }

}

Output
number of years: 61
number of months: 4


Also, you would need a Pluralsight membership to get access to this course, which costs around $29 per month or $299 annually (14% discount). 

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 5000+ online courses on all the latest topics like front-end and back-end development, machine learning, etc. It also includes interactive quizzes, exercises, and the latest certification material. 

It's more like Netflix for Software Developers and Since learning is an important part of our job, Plurlasight membership is a great way to stay ahead of your competition. 

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.




Things to Remember

1) You can calculate the difference between dates by subtracting milliseconds because of java.util.Date always represents a date as milliseconds from 1st January UTC, but you need to address several dates time-related issues like leap seconds, daylight saving times, leap years, different number of days in months, etc.

2) By using Jodatime, you will get a cleaner API to perform basic date-time arithmetic. It provides classes like Days, Months and Years to easily calculate days between two dates as well as months and year between them.

3) If you are using Java 8, then use a new Date and Time API. It is inspired by JodaTime and provides similar API to cleanly perform date arithmetic in Java.

4) You can use TimeUnit class to do conversion between different time units e.g. milliseconds to seconds, minutes, hours, etc.

5) Calendar class does provide some support but its limited to obtaining individual field and manually calculating differences.

That's all about how to calculate the difference between two dates in Java. Glad that we have Calendar class to do all the heavy lifting, but it's not smooth. Java 8 Date and Time has already addressed these issues. If you are running on Java 8, there is no way you should use existing Date and Calendar API.

Further Learning
The Complete Java MasterClass
What's New in Java 8
Java SE 8 for Programmers (book)
Refactoring to Java 8 Streams and Lambdas Self- Study Workshop

Other Java 8 Date and Time tutorial you may like to explore:
  • The 2020 Java Developer RoadMap (guide)
  • How to compare two dates in Java? (tutorial)
  • How to get current Timestamp value in Java? (tutorial)
  • 10 Things Java Developer should learn in 2020 (article)
  • How to convert String to LocalDateTime in Java 8? (example)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
  • How to convert Date to LocalDateTime in Java 8? (tutorial)
  • How to get current date and time in Java 6? (tutorial)
  • How to parse String to Date using JodaTime library? (example)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
  • How to convert String to LocalDateTime in Java 8 (tutorial)
  • How to become a better Java Programmer (article)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

No comments:

Post a Comment