Sub topic 13
Counting Units Between Two Temporals with ChronoUnit
The earlier chapters showed that Period gives you a mix of years, months, and days, and Duration gives you hours, minutes, and seconds. Sometimes you want a single number instead. How many days until a deadline? How many minutes did a task take? ChronoUnit answers those questions.
What ChronoUnit Is
ChronoUnit is an enum in the java.time.temporal package. An enum is a Java type with a fixed list of named values. Each value of ChronoUnit is one unit of time, such as DAYS, HOURS, or MONTHS.
A temporal is any java.time object that holds a date, a time, or both, such as LocalDate, LocalTime, LocalDateTime, Instant, or ZonedDateTime.
Every unit has a between method. You pass it two temporals, and it returns a long that holds the count of whole units from the first to the second.
| Unit | Meaning | Typical use |
|---|---|---|
| `NANOS`, `MICROS`, `MILLIS` | Fractions of a second | Timing code |
| `SECONDS`, `MINUTES`, `HOURS` | Clock units | Elapsed time |
| `HALF_DAYS` | 12 hours (AM/PM) | Rarely used |
| `DAYS`, `WEEKS` | Calendar days and 7-day weeks | Deadlines, ages in days |
| `MONTHS`, `YEARS` | Calendar months and years | Subscriptions, ages |
| `DECADES`, `CENTURIES`, `MILLENNIA` | Groups of years | History data |
Your First Count
The program below measures the gap between two dates in several units at once.
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class CountUnits {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2020, 1, 15);
LocalDate end = LocalDate.of(2024, 3, 10);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 1516
System.out.println(ChronoUnit.WEEKS.between(start, end)); // 216
System.out.println(ChronoUnit.MONTHS.between(start, end)); // 49
System.out.println(ChronoUnit.YEARS.between(start, end)); // 4
System.out.println(Period.between(start, end)); // P4Y1M24D
}
}Look at the last two lines. Period says "4 years, 1 month, and 24 days." ChronoUnit.MONTHS says "49 months." Both describe the same gap. The Period splits it into parts, and ChronoUnit gives one total.
Rule 1: Only Whole Units Count
between counts complete units only. Any leftover part is dropped. This is called truncation, which means cutting off the remainder instead of rounding.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class WholeUnits {
public static void main(String[] args) {
// January 31 to February 29 is not a full month
LocalDate a = LocalDate.of(2024, 1, 31);
LocalDate b = LocalDate.of(2024, 2, 29);
System.out.println(ChronoUnit.MONTHS.between(a, b)); // 0
// One minute short of a full day
LocalDateTime t1 = LocalDateTime.of(2024, 1, 1, 10, 0);
LocalDateTime t2 = LocalDateTime.of(2024, 1, 2, 9, 59);
System.out.println(ChronoUnit.DAYS.between(t1, t2)); // 0
System.out.println(ChronoUnit.HOURS.between(t1, t2)); // 23
}
}From January 31 to February 29 is 29 days, but a full month would end on February 31, and that date does not exist. Java does not count it as a month. In the same way, 23 hours and 59 minutes is not a full day, so the day count is 0.
Rule 2: Order Matters
The first argument is the start and the second is the end. If the end comes before the start, the result is negative.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Direction {
public static void main(String[] args) {
LocalDate first = LocalDate.of(2024, 3, 1);
LocalDate tenth = LocalDate.of(2024, 3, 10);
System.out.println(ChronoUnit.DAYS.between(first, tenth)); // 9
System.out.println(ChronoUnit.DAYS.between(tenth, first)); // -9
// until() does the same job, called on the start value
System.out.println(first.until(tenth, ChronoUnit.DAYS)); // 9
}
}The end date is exclusive, meaning it is not counted. From March 1 to March 10 is 9 days, not 10. If you want to count both ends, such as the number of days in a hotel booking including the checkout day, add 1 yourself.
start.until(end, unit) gives the same answer as unit.between(start, end). Use whichever reads better to you.
Counting with Times and Instants
ChronoUnit works the same way with times of day and with instants.
import java.time.Instant;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class TimeCounts {
public static void main(String[] args) {
LocalTime open = LocalTime.of(9, 15);
LocalTime close = LocalTime.of(17, 45);
System.out.println(ChronoUnit.HOURS.between(open, close)); // 8
System.out.println(ChronoUnit.MINUTES.between(open, close)); // 510
Instant sent = Instant.parse("2024-07-01T13:00:00Z");
Instant received = Instant.parse("2024-07-01T13:00:45.500Z");
System.out.println(ChronoUnit.SECONDS.between(sent, received)); // 45
System.out.println(ChronoUnit.MILLIS.between(sent, received)); // 45500
}
}The shop is open 8.5 hours, but HOURS reports 8 because of truncation. If you need the half hour, count in MINUTES and divide, or use Duration.
Rule 3: The Unit Must Fit the Type
A LocalDate has no clock time. Asking how many hours lie between two LocalDate values makes no sense, so Java throws an UnsupportedTemporalTypeException. An exception is an error object that stops normal flow unless you catch it.
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
public class WrongUnit {
public static void main(String[] args) {
LocalDate a = LocalDate.of(2024, 1, 1);
LocalDate b = LocalDate.of(2024, 1, 2);
System.out.println(a.isSupported(ChronoUnit.HOURS)); // false
try {
ChronoUnit.HOURS.between(a, b);
} catch (UnsupportedTemporalTypeException e) {
System.out.println(e.getMessage()); // Unsupported unit: Hours
}
Instant now = Instant.parse("2024-01-01T00:00:00Z");
System.out.println(now.isSupported(ChronoUnit.DAYS)); // true
System.out.println(now.isSupported(ChronoUnit.MONTHS)); // false
}
}An Instant supports units up to DAYS. It has no calendar, so it cannot count months or years. Call isSupported first if you are unsure.
| Type | Supported units |
|---|---|
| `LocalDate` | `DAYS` and larger |
| `LocalTime` | `NANOS` up to `HALF_DAYS` |
| `LocalDateTime`, `ZonedDateTime`, `OffsetDateTime` | All units |
| `Instant` | `NANOS` up to `DAYS` |
Edge Case: Daylight Saving Time
With ZonedDateTime, date units such as DAYS follow the calendar. Time units such as HOURS follow real elapsed time. On a day when clocks jump forward, those two answers can disagree.
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class DstCount {
public static void main(String[] args) {
ZoneId ny = ZoneId.of("America/New_York");
ZonedDateTime start = LocalDate.of(2024, 3, 10).atStartOfDay(ny);
ZonedDateTime end = start.plusDays(1);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 1
System.out.println(ChronoUnit.HOURS.between(start, end)); // 23
}
}It is one calendar day but only 23 real hours. Decide which one your program needs. A daily alarm cares about calendar days. A billing meter that charges by the hour cares about real hours.
Adding with ChronoUnit
You can also use a unit to move a date. plus(amount, unit) and minus(amount, unit) return a new object, as always in java.time.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class AddUnits {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2024, 11, 5);
System.out.println(today.plus(2, ChronoUnit.WEEKS)); // 2024-11-19
System.out.println(today.minus(1, ChronoUnit.DECADES)); // 2014-11-05
}
}Common Mistakes
- Using
Period.getDays()when you want total days. UseChronoUnit.DAYS.betweeninstead. - Forgetting that results are truncated. Count in a smaller unit if partial units matter.
- Swapping start and end, which flips the sign.
- Expecting the end to be included. It is not, so add 1 for an inclusive count.
- Asking for a unit the type does not support, such as
HOURSonLocalDate.
Exercise
A trial starts on 2024-02-10 and ends on 2024-05-09. What do ChronoUnit.MONTHS.between(start, end) and ChronoUnit.DAYS.between(start, end) return, and why is the month count not 3?
Show answer
MONTHS returns 2 and DAYS returns 89 (19 days left in February, 31 in March, 30 in April, and 9 in May). The month count is 2 because a third full month would end on 2024-05-10, which is after the end date, so the partial month is truncated.
Exercise
Write one line that prints how many whole minutes passed between two Instant values named begin and finish, and explain what happens if finish is earlier than begin.
Show answer
System.out.println(ChronoUnit.MINUTES.between(begin, finish)); If finish is earlier than begin, the result is negative, because between measures from the first argument to the second.
Exercise
Why does ChronoUnit.HOURS.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 1, 2)) fail, and how could you get 24 instead?
Show answer
LocalDate has no time of day, so it does not support HOURS and Java throws UnsupportedTemporalTypeException. Convert both dates first, for example with atStartOfDay(), to get LocalDateTime values, then count HOURS between them to get 24.