Saturday, February 8, 2020

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

Oracle Java Study Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Learning

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.

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.

Oracle Java Study Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Learning

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). 

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.

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.

Source: java67.com

Related Posts

0 comments:

Post a Comment