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