Sub topic 13
Counting Units Between Two Temporals with ChronoUnit
Sometimes you need one number, such as "how many days until the deadline?" A Period gives you years, months, and days as separate parts. A Duration gives you hours, minutes, and seconds. ChronoUnit gives you a single total count in the unit you choose.
What ChronoUnit Is
ChronoUnit is an enum. An enum is a fixed list of named values. Each value is a unit of time, for example DAYS, WEEKS, MONTHS, HOURS, or MINUTES. Each unit has a between method that counts how many whole units fit between two temporals. A temporal is any java.time object that holds a date or time, such as LocalDate or LocalTime.
A Worked Example
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Counting {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2020, 1, 15);
LocalDate end = LocalDate.of(2024, 3, 10);
System.out.println(Period.between(start, end)); // P4Y1M24D
System.out.println(ChronoUnit.MONTHS.between(start, end)); // 49
System.out.println(ChronoUnit.DAYS.between(start, end)); // 1516
System.out.println(start.until(end, ChronoUnit.DAYS)); // 1516
LocalTime open = LocalTime.of(9, 0);
LocalTime close = LocalTime.of(10, 59);
System.out.println(ChronoUnit.HOURS.between(open, close)); // 1
System.out.println(ChronoUnit.MINUTES.between(open, close)); // 119
System.out.println(ChronoUnit.DAYS.between(end, start)); // -1516
}
}Here is what the output shows:
Periodsplits the gap into parts: 4 years, 1 month, 24 days.MONTHS.betweenreturns the gap as one total: 49 whole months.start.until(end, unit)gives the same answer asunit.between(start, end). Use whichever reads better to you.- 9:00 to 10:59 is 1 hour, not 2. Only whole units count, and the leftover part is dropped.
- If the end comes before the start, the result is negative.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting rounding | 9:00 to 10:59 gives 1 hour | Count in a smaller unit, such as minutes |
| Using a time unit on dates | `HOURS.between` on two `LocalDate` values throws `UnsupportedTemporalTypeException` | Use `LocalDateTime` or a date unit like `DAYS` |
| Swapping arguments | You get a negative number | Put the earlier temporal first |
Exercise
What does ChronoUnit.DAYS.between(LocalDate.of(2024, 12, 31), LocalDate.of(2024, 1, 1)) return, and why?
Show answer
It returns -365. There are 365 days between January 1 and December 31, 2024. The end date comes before the start date, so the result is negative.
Exercise
A movie starts at 19:30 and ends at 21:15. What do ChronoUnit.HOURS.between and ChronoUnit.MINUTES.between return for these two LocalTime values?
Show answer
HOURS.between returns 1, because only whole hours count and the extra 45 minutes are dropped. MINUTES.between returns 105.