Temporal API
Shared capabilities of different time classes
LocalDate, LocalDateTime,
Instant, and ZonedDateTime solve different problems,
but many of their operations are similar: read a field, add a unit of time,
check whether a field is supported, or apply an adjustment.
These shared capabilities are organized around the Temporal API.
In ordinary application code, concrete classes are often enough. The Temporal API becomes especially useful when you need to write a generic operation or use standard units and adjustments without implementing calendar logic manually.
Temporal and TemporalAccessor
TemporalAccessor describes an object from which temporal fields can be read.
Temporal adds the ability to create adjusted values through operations such as
with(), plus(), and minus().
For example, a formatter can work with TemporalAccessor,
so one formatting mechanism can support different date and time classes.
ChronoUnit — units of time
Instead of using a separate method for every situation, a unit can be passed explicitly.
ChronoUnit contains standard units from nanoseconds to years.
LocalDate date = LocalDate.of(2026, 9, 18);
LocalDate later = date.plus(10, ChronoUnit.DAYS);
long days = ChronoUnit.DAYS.between(date, later);
Not every temporal type supports every unit.
For example, LocalDate has no time of day,
so adding hours to it has no meaning and results in an error.
ChronoField — temporal fields
ChronoField represents standard fields such as day of month,
month of year, or hour of day. Specific methods such as getYear()
are usually easier to read, but fields are useful in generic code.
LocalDate date = LocalDate.of(2026, 9, 18);
int day = date.get(ChronoField.DAY_OF_MONTH);
TemporalAdjusters — ready-made calendar adjustments
Instead of writing manual loops, you can use ready-made rules from TemporalAdjusters.
For example, to get the last day of a month:
LocalDate date = LocalDate.of(2026, 9, 18);
LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
Or the next Monday:
LocalDate monday = date.with(
TemporalAdjusters.next(DayOfWeek.MONDAY)
);
LocalDate parameter
is usually clearer than an abstract Temporal.
Common interfaces are useful when that generality is part of the task.