How to Calculate Date Differences Using ChronoUnit

You can calculate date differences in Java using the ChronoUnit enum from the java.time package. The ChronoUnit class is used to measure the amount of time between two temporal objects (e.g., LocalDate, LocalDateTime, etc.) in terms of specific time units like DAYS, MONTHS, YEARS, etc.

Here’s an example of how to calculate the difference between two LocalDate objects in various time units:

Example Code

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DateDifferenceExample {
    public static void main(String[] args) {
        // Define two dates
        LocalDate date1 = LocalDate.of(2023, 1, 1);
        LocalDate date2 = LocalDate.of(2025, 8, 7);

        // Calculate differences using ChronoUnit
        long daysBetween = ChronoUnit.DAYS.between(date1, date2);
        long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
        long yearsBetween = ChronoUnit.YEARS.between(date1, date2);

        // Print results
        System.out.println("Days between: " + daysBetween);
        System.out.println("Months between: " + monthsBetween);
        System.out.println("Years between: " + yearsBetween);
    }
}

Output

Days between: 949
Months between: 31
Years between: 2

Explanation

  1. between() Method:
    • The ChronoUnit.between() method takes two temporal objects as parameters and returns the difference in the specified unit (e.g., days, months, or years).
    • Ensure that the objects provided are compatible (e.g., both are LocalDate or LocalDateTime).
  2. Units of Measurement:
    • The ChronoUnit enum provides different constants such as DAYS, HOURS, WEEKS, MONTHS, YEARS, etc., to calculate differences at the desired granularity.
  3. Signed Differences:
    • The result may be negative if the first date is later than the second date. You can swap the dates if you want an absolute difference.

Other Temporal Types

ChronoUnit also works with other temporal types such as LocalDateTime, ZonedDateTime, Instant, etc. For example:

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeDifference {
    public static void main(String[] args) {
        LocalDateTime dateTime1 = LocalDateTime.of(2023, 1, 1, 10, 0);
        LocalDateTime dateTime2 = LocalDateTime.of(2025, 8, 7, 12, 30);

        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);

        System.out.println("Hours between: " + hoursBetween);
        System.out.println("Minutes between: " + minutesBetween);
    }
}

This will give you the time differences in hours and minutes.

Note

  • ChronoUnit.WEEKS may not align perfectly with ChronoUnit.DAYS due to week boundaries.
  • Always validate whether the specific ChronoUnit applies to the temporal objects you’re comparing (e.g., you can’t use HOURS on LocalDate because it lacks time information).

How do I use ChronoUnit enumeration?

ChronoUnit is an enumeration that provides static constants representing the units of time in the date-time API in Java. These constants include DAYS, HOURS, SECONDS, etc., that are often used to measure a quantity of time with respect to the specifics of a calendar system.

Here’s an example of how you can use the ChronoUnit enumeration:

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class ChronoUnitExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();

        LocalDateTime tenDaysLater = now.plus(10, ChronoUnit.DAYS);
        System.out.println("Date 10 days from now: " + tenDaysLater);

        LocalDateTime twoHoursLater = now.plus(2, ChronoUnit.HOURS);
        System.out.println("Time 2 hours from now: " + twoHoursLater);
    }
}

Output:

Date 10 days from now: 2024-01-27T21:24:22.397516900
Time 2 hours from now: 2024-01-17T23:24:22.397516900

In this sample, we use the plus method of LocalDateTime that takes two parameters: a long amount to add and a TemporalUnit. We pass to it a constant from ChronoUnit.

We can also measure the difference between two date-time objects, like so:

package org.kodejava.datetime;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class DateTimeDiff {
    public static void main(String[] args) {
        LocalTime start = LocalTime.of(14, 30);
        LocalTime end = LocalTime.of(16, 30);

        long elapsedMinutes = ChronoUnit.MINUTES.between(start, end);
        System.out.println("Elapsed minutes: " + elapsedMinutes);
    }
}

Output:

Elapsed minutes: 120

In the above example, the between method from ChronoUnit was used to calculate the difference in minutes between start and end times.

How do I calculate days between two dates excluding weekends and holidays?

The code snippet below shows you a simple way to calculate days between two dates excluding weekends and holidays. As an example, you can use this function for calculating work days. The snippet utilize the java.time API and the Stream API to calculate the value.

What we do in the code below can be described as the following:

  • Create a list of holidays. The dates might be read from a database or a file.
  • Define filter Predicate for holidays.
  • Define filter Predicate for weekends.
  • These predicates will be use for filtering the days between two dates.
  • Define the startDate and the endDate to be calculated.
  • Using Stream.iterate() we iterate the dates, filter it based on the defined predicates.
  • Finally, we get the result as list.
  • The actual days between is the size of the list, workDays.size().
package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class DaysBetweenDates {
    public static void main(String[] args) {
        List<LocalDate> holidays = new ArrayList<>();
        holidays.add(LocalDate.of(2022, Month.DECEMBER, 26));
        holidays.add(LocalDate.of(2023, Month.JANUARY, 2));

        Predicate<LocalDate> isHoliday = holidays::contains;
        Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY
                || date.getDayOfWeek() == DayOfWeek.SUNDAY;

        LocalDate startDate = LocalDate.of(2022, Month.DECEMBER, 23);
        LocalDate endDate = LocalDate.of(2023, Month.JANUARY, 3);
        System.out.println("Start date = " + startDate);
        System.out.println("End date   = " + endDate);

        // Days between startDate inclusive and endDate exclusive
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println("Days between = " + daysBetween);

        List<LocalDate> workDays = Stream.iterate(startDate, date -> date.plusDays(1))
                .limit(daysBetween)
                .filter(isHoliday.or(isWeekend).negate())
                .toList();

        long actualDaysBetween = workDays.size();
        System.out.println("Actual days between = " + actualDaysBetween);
    }
}

Running the code snippet above give us the following result:

Start date = 2022-12-23
End date   = 2023-01-03
Days between = 11
Actual days between = 5

How to find the difference between two LocalDateTime objects?

In the previous post, How do I find the difference between two times?, we get the difference between two LocalTime objects in seconds measurement. In this example we will get the difference between two LocalDateTime objects and get the difference between these objects in years, months, days, hours, minutes, seconds and milliseconds.

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeDiff {
    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.of(2021, Month.JANUARY, 10, 10, 0, 30);
        LocalDateTime to = LocalDateTime.now();

        LocalDateTime fromTemp = LocalDateTime.from(from);
        long years = fromTemp.until(to, ChronoUnit.YEARS);
        fromTemp = fromTemp.plusYears(years);

        long months = fromTemp.until(to, ChronoUnit.MONTHS);
        fromTemp = fromTemp.plusMonths(months);

        long days = fromTemp.until(to, ChronoUnit.DAYS);
        fromTemp = fromTemp.plusDays(days);

        long hours = fromTemp.until(to, ChronoUnit.HOURS);
        fromTemp = fromTemp.plusHours(hours);

        long minutes = fromTemp.until(to, ChronoUnit.MINUTES);
        fromTemp = fromTemp.plusMinutes(minutes);

        long seconds = fromTemp.until(to, ChronoUnit.SECONDS);
        fromTemp = fromTemp.plusSeconds(seconds);

        long millis = fromTemp.until(to, ChronoUnit.MILLIS);

        System.out.println("From = " + from);
        System.out.println("To   = " + to);
        System.out.printf("The difference is %s years, %s months, %s days, " +
                        "%s hours, %s minutes, %s seconds, %s millis",
                years, months, days, hours, minutes, seconds, millis);
    }
}

The result of the code snippet above when executed is:

From = 2021-01-10T10:00:30
To   = 2021-11-17T15:07:37.913247900
The difference is 0 years, 10 months, 7 days, 5 hours, 7 minutes, 7 seconds, 913 millis