difference between two dates

Difference between two dates in Java using ChronoUnit

In this quick sneppet, you will explore java.time (Java 8) LocalDate, LocalDateTime, ZonedDateTime and ChronoUnit to find difference between two dates.

difference between two dates

ChronoUnit is the implementation class of java.time.TemporalUnit interface. The most commonly used units are defined in ChronoUnit e.g., WEEKS, DAYS, HOURS, MINUTES, SECONDS etc.,.

Each unit provides a method called “between” to calculate the difference between two temporal objects for the specified unit. Let’s see how to calculate difference between two LocalDate dates in DAYS.

Difference between two dates – LocalDate:

LocalDate ldtoday = LocalDate.now();
LocalDate fiveDaysBefore = ldtoday.minusDays(5);
long diff1 = ChronoUnit.DAYS.between(fiveDaysBefore, ldtoday);
System.out.println(diff1);

LocalDateTime:

LocalDateTime ldttoday = LocalDateTime.now();
LocalDateTime fiftyHoursBehind = ldttoday.minusHours(50);
long diff2 = ChronoUnit.HOURS.between(fiftyHoursBehind, ldttoday);
System.out.println(diff2);

ZonedDateTime:

ZonedDateTime startDate = ZonedDateTime.now();
ZonedDateTime endDate = ZonedDateTime.now().plusDays(5);
long diff3 = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println(diff3);

You can also use external libraries like JodaTime. Note, the project Oracle Java SE 8 Date and Time has been jointly led by the author Stephen Colebourne of Joda-Time and Oracle.

External Library  Joda-Time:

Let us see how to implement difference between two LocalDate using Joda-time. You can add the dependency in your POM.xml as shown below.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.9</version>
</dependency>

Below is the sample code for LocalDate case

LocalDate today = LocalDate.now();
LocalDate fiveDaysBefore = today.minusDays(5);
	 
Period period = new Period(today, fiveDaysBefore);
long diff = Math.abs(period.getDays());
System.out.println(diff);

Further Learning

References

Leave a Reply

avatar
  Subscribe  
Notify of