Sunday, August 1, 2021

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 it's 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 these Java 8 online courses, 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 these free Java programming online courses, 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 the difference between two dates in Java as it's very clear and readable and you don't need to use any external library.  Here is the sample code example to find the number of days, months, and years between two dates in Java.

Btw, there is a lot to learn about the Date and Time API of Java 8, and you are interested, I suggest you check out these online Java 8 courses, 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  





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 years between them.

3) If you are using Java 8, then use a new Date and Time API. It is inspired by JodaTime and provides a 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 it's limited to obtaining individual fields and manually calculating differences.

That's all about how to calculate the difference between two dates in Java. I am glad that we have a 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 the existing Date and Calendar API.

Other Java 8 Date and Time tutorials you may like to explore:
  • The Java Developer RoadMap (guide)
  • How to compare two dates in Java? (tutorial)
  • How to get the current Timestamp value in Java? (tutorial)
  • 10 Things Java Developer should learn (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 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)
  • How to get the current date and time in Java 6? (tutorial)
  • How to parse String to Date using JodaTime library? (example)

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. 

1 comment:

Feel free to comment, ask questions if you have any doubt.