Java – Difference Between Two Dates

In this Java tutorial, we will look at the programs to find the difference between two dates in Java.

The initial programs use the new Java 8 date-time API. In the last program, we will learn to find the difference using Jodatime API which was available even before Java 8 release. If you are still not using Java 8, then JodaTime should be your first choice.

1. Date Difference using Java 8 APIs

Legacy Java classes have always been lacking enough support to express dates and time periods in an effective way. Java 8 made the first attempt to upgrade this date/time API.

1.1. ChronoUnit.between() for Difference in All Time Units

The ChronoUnit instance represents a standard set of date periods units. We can use its different types of instances to find the difference in specific time measures.

LocalDate dateOfBirth = LocalDate.of(1980, Month.JULY, 4);
LocalDate currentDate = LocalDate.now();

long diffInDays = ChronoUnit.DAYS.between(dateOfBirth, currentDate);
long diffInMonths = ChronoUnit.MONTHS.between(dateOfBirth, currentDate);
long diffInYears = ChronoUnit.YEARS.between(dateOfBirth, currentDate);

We can use ChronoUnit to know the difference in smaller time units e.g. milliseconds, minutes etc. But in that case, we will have to use LocalDateTime in place of LocalDate, because LocalDate does not have any time information associated with it.

LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();

long diffInNano = ChronoUnit.NANOS.between(dateTime, dateTime2);
long diffInSeconds = ChronoUnit.SECONDS.between(dateTime, dateTime2);
long diffInMilli = ChronoUnit.MILLIS.between(dateTime, dateTime2);
long diffInMinutes = ChronoUnit.MINUTES.between(dateTime, dateTime2);
long diffInHours = ChronoUnit.HOURS.between(dateTime, dateTime2);

We can even use the instances of ZonedDateTime to know the difference when both dates are in different time zones.

1.2. Period.between() for Difference in Days, Months and Years

The between() method returns a Period consisting of the number of years, months, and days between two dates.

  • Note that the start date is included, but the end date is excluded.
  • The result of this method can be a negative period if the end is before the start.

As stated above, Period class represents the time difference in the format of “x years, y months and z days”. So, when we call its getDays() method, it returns only the “z days” part.

LocalDate endofCentury = LocalDate.of(2014, 01, 01);
LocalDate now = LocalDate.now();

Period diff = Period.between(endofCentury, now);

System.out.printf("Difference is %d years, %d months and %d days old",
					diff.getYears(), diff.getMonths(), diff.getDays());

2.3. Duration.between() for Difference in Hours, Minutes and Seconds

Duration represents time difference in a smaller time-based amount of time such as hours, minutes, seconds, nanoseconds etc.

LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();

int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();

Above all 3 programs have enough readability as well as the flexibility to know the difference between dates in multiple and different time units.

2. JodaTime Library

2.1. Maven

Start with importing the library in the project.

pom.xml
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10</version>
</dependency>

2.2. Demo

As we all prefer readability, I will suggest using the Jodatime library (which actually inspired Java 8 date/time APIs).

DateTime dateOfBirth = new DateTime(1988, 7, 4, 0, 0, GregorianChronology.getInstance());
DateTime currentDate = new DateTime();

Days diffInDays = Days.daysBetween(dateOfBirth, currentDate);
Hours diffInHours = Hours.hoursBetween(dateOfBirth, currentDate);
Minutes diffInMinutes = Minutes.minutesBetween(dateOfBirth, currentDate);
Seconds seconds = Seconds.secondsBetween(dateOfBirth, currentDate);

3. Legacy Java Classes

For reference purposes, let us see an example to find the date difference using the java.util.Date and SimpleDateFormat classes.

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DateDifference {
  public static void main(final String[] args) {
    // First Date
    Date today = new Date();

    // Second Date
    Date sameDayNextMonth = new Date();
    sameDayNextMonth.setMonth(today.getMonth() + 1);

    long days = getDateDiff(today, sameDayNextMonth, TimeUnit.DAYS); // 31
    long hours = getDateDiff(today, sameDayNextMonth, TimeUnit.HOURS); // 744
    long minutes = getDateDiff(today, sameDayNextMonth, TimeUnit.MINUTES); // 44640
    long seconds = getDateDiff(today, sameDayNextMonth, TimeUnit.SECONDS); // 2678400
    long mills = getDateDiff(today, sameDayNextMonth, TimeUnit.MILLISECONDS); // 2678400000
  }

  public static long getDateDiff(final Date date1, final Date date2,
    final TimeUnit timeUnit) {
    long diffInMillies = date2.getTime() - date1.getTime();

    return timeUnit.convert(diffInMillies, timeUnit.MILLISECONDS);
  }
}

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial