Java ChronoUnit Class

ChronoUnit is an enum class introduced in Java 8, belonging to thejava.time.temporalpackage.

ChronoUnit defines a set of standard time units used to represent different granularities of date and time. ChronoUnit is mainly used with the Java 8 Date-Time API (such asLocalDate、LocalTime、LocalDateTimeetc.) for time calculation and comparison.


Core Features

1. Representation of Time Units

ChronoUnit provides various time units from nanoseconds to centuries, including:

  • NANOS: Nanoseconds
  • MICROS: Microseconds
  • MILLIS: Milliseconds
  • SECONDS: Seconds
  • MINUTES: Minutes
  • HOURS: Hours
  • HALF_DAYS: Half-day (12 hours)
  • DAYS: Days
  • WEEKS: Weeks
  • MONTHS: Months
  • YEARS: Years
  • DECADES: Decades
  • CENTURIES: Centuries
  • MILLENNIA: Millennia
  • ERAS: Eras

2. Time Calculation

ChronoUnit can be used withTemporalobjects (such asLocalDate) to perform addition and subtraction operations on time.

Example

LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); // Add one week
LocalDate lastMonth = today.minus(1, ChronoUnit.MONTHS); // Subtract one month

3. Time Difference Calculation

You can use thebetween()method to calculate the difference between two time points.

Example

LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
long days = ChronoUnit.DAYS.between(start, end); // Calculate day difference

Detailed Explanation of Common Methods

1. between() Method

Calculates the time difference between two Temporal objects.

Example

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive)

Example:

Example

LocalDateTime start = LocalDateTime.of(2023, 1, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2023, 1, 2, 12, 0);
long hours = ChronoUnit.HOURS.between(start, end); // 36 hours

2. addTo() Method

Adds the time unit to a Temporal object.

Example

public Temporal addTo(Temporal temporal, long amount)

Example:

Example

LocalTime time = LocalTime.of(14, 30);
LocalTime newTime = (LocalTime) ChronoUnit.HOURS.addTo(time, 3); // 17:30

3. isSupportedBy() Method

Checks whether a Temporal object supports the time unit.

Example

public boolean isSupportedBy(Temporal temporal)

Example:

Example

LocalDate date = LocalDate.now();
boolean supported = ChronoUnit.HOURS.isSupportedBy(date); // false, because LocalDate does not support the hour unit

Practical Application Examples

1. Calculating Age

Example

LocalDate birthDate = LocalDate.of(1990, 5, 15);
LocalDate now = LocalDate.now();
long age = ChronoUnit.YEARS.between(birthDate, now);
System.out.println("Age: " + age + " years old");

2. Calculating Project Duration

Example

LocalDateTime projectStart = LocalDateTime.of(2023, 1, 1, 9, 0);
LocalDateTime projectEnd = LocalDateTime.of(2023, 6, 30, 18, 0);
long months = ChronoUnit.MONTHS.between(projectStart, projectEnd);
long days = ChronoUnit.DAYS.between(projectStart, projectEnd);
System.out.println("Project duration: " + months + " months, or " + days + " days");

3. Generating Date Sequences

Example

LocalDate start = LocalDate.of(2023, 1, 1);
List<LocalDate> dates = new ArrayList<>();
for (int i = 0; i < 7; i++) {
    dates.add(start.plus(i, ChronoUnit.DAYS));
}

Simple Example

Example

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

public class ChronoUnitExample {
    public static void main(String[] args) {
        // 1. Calculate the number of days between two dates
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        long daysBetween = ChronoUnit.DAYS.between(today, nextWeek);
        System.out.println("Days between today and the same day next week: " + daysBetween);
       
        // 2. Time addition and subtraction
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Current time: " + now);
       
        LocalDateTime in2Hours = now.plus(2, ChronoUnit.HOURS);
        System.out.println("Two hours later: " + in2Hours);
       
        LocalDateTime yesterday = now.minus(1, ChronoUnit.DAYS);
        System.out.println("This time yesterday: " + yesterday);
       
        // 3. Calculate the number of hours between two time points
        long hoursBetween = ChronoUnit.HOURS.between(yesterday, now);
        System.out.println("Hours from this time yesterday to now: " + hoursBetween);
       
        // 4. Using different time units
        System.out.println("Difference in minutes: " + ChronoUnit.MINUTES.between(yesterday, now));
        System.out.println("Difference in seconds: " + ChronoUnit.SECONDS.between(yesterday, now));
       
        // 5. Check whether a time unit supports a specific type
        System.out.println("Does DAYS support LocalDate: " + ChronoUnit.DAYS.isSupportedBy(today));
        System.out.println("Does HOURS support LocalDate: " + ChronoUnit.HOURS.isSupportedBy(today));
    }
}

The output is:

今天和下周今天之间的天数: 7
当前时间: 2025-05-01T11:22:22.247669
两小时后: 2025-05-01T13:22:22.247669
昨天此时: 2025-04-30T11:22:22.247669
昨天此时到现在的小时数: 24
相差的分钟数: 1440
相差的秒数: 86400
DAYS是否支持LocalDate: true
HOURS是否支持LocalDate: false

Calculating Age

Example

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

public class AgeCalculator {
    public static void main(String[] args) {
        LocalDate birthDate = LocalDate.of(1990, 5, 15);
        LocalDate currentDate = LocalDate.now();
       
        long years = ChronoUnit.YEARS.between(birthDate, currentDate);
        long months = ChronoUnit.MONTHS.between(birthDate, currentDate) % 12;
        long days = ChronoUnit.DAYS.between(
            birthDate.plusYears(years).plusMonths(months),
            currentDate
        );
       
        System.out.printf("Age: %d years %d months %d days%n", years, months, days);
    }
}

The output is:

年龄: 34 年 11 个月 16 天

Notes

  1. Time unit support: Not all Temporal objects support all ChronoUnit. For example,LocalDatedoes not supportHOURSorMINUTES。

  2. Negative value handling: When the first parameter is later than the second,between()the method will return a negative value.

  3. Precision issues: For larger time units (such as MONTHS or YEARS), calculations may not be completely accurate, because the number of days in these units is not fixed.

  4. Performance considerations: For frequent time calculations, using ChronoUnit is more efficient and less error-prone than manual calculation.


Comparison with Other Classes

1. ChronoUnit vs TimeUnit

  • TimeUnitMainly used for thread sleeping and concurrent operations, with finer time unit granularity (nanoseconds to days)
  • ChronoUnitDesigned specifically for the Date-Time API, supporting larger time units (weeks to millennia)

2. ChronoUnit vs Duration/Period

  • DurationUsed for precise amounts of time (nanoseconds to days)
  • PeriodUsed for date amounts (days to years)
  • ChronoUnitProvides more flexible unit selection and calculation methods
Other Extensions