Thor
Thor

Reputation: 10058

why ZonedDateTime class does not implement TemporalAdjuster interface

I'm currently studying java.time API and I have noticed that majority of class (e.g. LocalDate, OffsetDateTime) in java.time implement TemporalAdjuster interface, but ZonedDateTime does not. I was just wondering why this is the case? Why exclude ZonedDateTime from implementing TemporalAdjuster interface?

Upvotes: 8

Views: 284

Answers (1)

JodaStephen
JodaStephen

Reputation: 63405

A TemporalAdjuster changes another temporal object via the TemporalAdjuster.adjustInto(Temporal) method. The Temporal interface allows the individual fields to be altered via Temporal.with(TemporalField, long).

LocalDate can implement TemporalAdjuster because its state consists entirely of temporal fields (year, month, day-of-month). As such, the implementation in LocalDate.adjustInto(Temporal) can call Temporal.with(TemporalField, long) passing the year, month and day (it actually uses ChronoField.EPOCH_DAY, which is a composite of year, month and day).

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

ZonedDateTime cannot implement TemporalAdjuster because its state includes a ZoneId, which is not a temporal field, thus cannot be passed to Temporal.with(TemporalField, long). ie. it is not possible to change the time-zone of a temporal class via the Temporal interface.

Given that ZonedDateTime includes all the possible date-time fields, this restriction has little effect in practice.

Upvotes: 7

Related Questions