1. Home
  2. Coding
  3. How to calculate the difference between Dates in Java

How to calculate the difference between Dates in Java

Share

In this guide, we will see how to calculate the difference between two dates in Java. This is straightforward and can be done using core Java (from Java 8), or taking advantage of different libraries to help us get the job done, like Joda-Time.

In the next sections we will see two different approaches to calculate the differences between dates:

Dates difference in core Java

The easiest way is to use the Duration class (java.time.Duration, available since Java 1.8). Given the fromDate and toDate variables, we can calculate the difference between the two dates in days just using the following line of code:

long days = Duration.between(fromDate.toInstant(), toDate.toInstant()).toDays();

Also, if we want to calculate the time between two dates in minutes, we can use the Duration class in a different way:

long minutes = Duration.between(fromDate.toInstant(), toDate.toInstant()).toMinutes();

The following code is a full example of the different ways you can use the Duration class for Dates calculations, with tests implemented:

/**
 * Convert a String to Date helper.
 * 
 * @param dateStr Date in String format
 * @return Parsed Date from String
 * @throws ParseException
 */
public Date stringToDate(String dateStr) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    return sdf.parse(dateStr);
}

/**
 * Get the difference between two dates in Days.
 * 
 * @param fromDate From
 * @param toDate   To
 * @return Days
 */
public long getDateDifferenceInDays(Date fromDate, Date toDate) {
    long days = Duration.between(fromDate.toInstant(), toDate.toInstant()).toDays();
    return days;
}

/**
 * Get the difference between two dates in Minutes
 * 
 * @param fromDate From
 * @param toDate   To
 * @return Minutes
 */
public long getDateDifferenceInMinutes(Date fromDate, Date toDate) {
    long minutes = Duration.between(fromDate.toInstant(), toDate.toInstant()).toMinutes();
    return minutes;
}

@Test
public void dateDifference_inDays() throws ParseException {
    Date fromDate = stringToDate("10/03/2020 10:00:00");
    Date toDate = stringToDate("17/03/2020 10:00:00");
    assertEquals(7, getDateDifferenceInDays(fromDate, toDate));
}

@Test
public void dateDifference_inMinutes() throws ParseException {
    Date fromDate = stringToDate("17/03/2020 15:30:00");
    Date toDate = stringToDate("17/03/2020 16:35:00");
    assertEquals(65, getDateDifferenceInMinutes(fromDate, toDate));
}

In particular, we have:

  • getDateDifferenceInDays: calculates the difference between the dates in days and returns it;
  • getDateDifferenceInMinutes: calculates the difference between the dates in minutes and returns it;
  • dateDifference_inDays: tests the getDateDifferenceInDays method;
  • dateDifference_inMinutes: tests the getDateDifferenceInMinutes method;
  • stringToDate: this method helps to convert a string into a date. For the purpose of this exercise, we are parsing a DateTime to explain the getDateDifferenceInMinutes methods. If we need a Date instead of a DateTime, we have to call the SimpleDateFormat class with the dd/MM/yyyy pattern. If you want to learn more about this topic, you can read our article on how to convert dates and strings in Java.

Dates difference using JodaTime

Another easy way to calculate differences between dates in Java is using the JodaTime library. Joda-Time helps us especially in previous versions of Java 8. Thanks to the many utilities for Dates and DateTimes, Joda-Time can help in calculating the difference between different time units.

First, we need to include the Joda-Time library in our project. If we are using Maven, we simply need to add the following line into our pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  ...

  <dependencies>
    ...

    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.10.10</version>
    </dependency>
  </dependencies>

  <build>
    ...
  </build>
</project>

Currently, the latest version of Joda-Time is 2.10.10. For the latest version, please refer to the official Joda-Time page.

Similarly to what we did before, to calculate the difference between two dates using Joda-Time we do:

@Test
public void dateDifference_jodaTime() throws IllegalArgumentException {
    LocalDate fromDate = LocalDate.parse("2020-03-10");
    LocalDate toDate = LocalDate.parse("2020-03-17");
    assertEquals(7, Days.daysBetween(fromDate, toDate).getDays());
}

At this point, the only difference is that we are using the LocalDate class from Joda-Time, which can handle the “string to Date” parsing by itself. Important note: be sure to import org.joda.time.LocalDate instead of java.time.LocalDate!

If you like our post, please share it: