简体   繁体   中英

why ZonedDateTime class does not implement TemporalAdjuster interface

I'm currently studying java.time API and I have noticed that majority of class (eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM