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.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.