This post will discuss how to calculate the difference between two dates in Java.

1. Using TimeUnit.convert() method

The idea is first to get the difference between two dates in milliseconds using the Date.getTime() method. Then we can use the convert() method from java.util.concurrent.TimeUnit enum to convert the given time duration in the given unit to the unit of the argument.

Download  Run Code

Output:

1440

 
Please note that the above code snippet doesn’t consider time zones as java.util.Date is always in UTC. Also, this won’t consider daylight savings.

2. Using java.time package

From Java 8 onward, we should use the java.time package that offers a lot of improvement over the existing Java date-time API. Here’s how we can calculate the difference between two dates as a Duration in Java 8 and above.

Download  Run Code

Output:

PT1704H5M40S

 
If you have a java.util.Date object, you should convert it into java.time.Instant and then calculate the elapsed time as a Duration.

Download  Run Code

Output:

PT3880H26M38.942S

3. Using Joda Time

Before Java 8, many Java projects have used the Joda-Time library for Date and Time classes. This is because the standard date and time classes before Java 8 are poor. But with the introduction of the java.time package in Java SE 8, the Joda-Time team have asked their users to migrate to java.time (JSR-310).

If you are using the Joda-Time library in your project and just want the total number of whole days between two dates, you can use the new Days class in version 1.4 of Joda-Time.

 
If you want to calculate the total number of days, weeks, months, and years between the two dates, you need a Period. By default, this will split the difference between the two date-times into parts, such as “1 month, 2 weeks, 4 days and 7 hours”.

 
You can control which fields get extracted using a PeriodType.

 
This example will return no weeks or time fields; thus, the previous example becomes “1 month and 18 days”.

That’s all about calculating the difference between two dates in Java.