Why the ZonedDateTime class does not implement the TemporalAdjuster interface

I am currently studying the java.time API, and I noticed that most classes (e.g. LocalDate , OffsetDateTime ) in the java.time interface implement TemporalAdjuster , but ZonedDateTime does not. I'm just wondering why this is? Why exclude ZonedDateTime from the TemporalAdjuster interface implementation?

+7
java time java-8 java-time
source share
1 answer

A TemporalAdjuster modifies another temporary object using the TemporalAdjuster.adjustInto(Temporal) method. The Temporal interface allows you to change individual fields using Temporal.with(TemporalField, long) .

LocalDate can implement TemporalAdjuster because its state consists entirely of time fields (year, month, day-month). Thus, an implementation in LocalDate.adjustInto(Temporal) can call Temporal.with(TemporalField, long) , passing year, month, and day (in fact, it uses ChronoField.EPOCH_DAY , which is part of the year, month, and day).

OffsetDateTime can implement TemporalAdjuster because its state also consists entirely of time fields (year, month, day-month, hour, minute, second, nanosecond and offset-seconds). So again, the implementation in OffsetDateTime.adjustInto(Temporal) can call Temporal.with(TemporalField, long) , passing the fields one at a time.

ZonedDateTime cannot implement TemporalAdjuster because its state includes ZoneId , which is not a temporary field, and therefore cannot be passed to Temporal.with(TemporalField, long) . i.e. It is not possible to change the time zone of a time class through the Temporal interface.

Considering that ZonedDateTime contains all possible date and time fields, this restriction has practically no effect in practice.

+6
source share

All Articles