Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
Thor Avatar asked Mar 16 '17 01:03

Thor


People also ask

What does ZonedDateTime do in Java?

ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times.

What is the difference between LocalDateTime and ZonedDateTime?

A LocalDateTime instance represents a point in the local timeline. It cannot represent an instant on the universal timeline without additional information such as an offset or time zone. A ZonedDateTime instance represents an instant in the universal timeline. It is the combination of date, time and zone information.

What is OffsetDateTime in Java?

OffsetDateTime is an immutable representation of a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value "2nd October 2007 at 13:45.30. 123456789 +02:00" can be stored in an OffsetDateTime .


1 Answers

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.

like image 159
JodaStephen Avatar answered Oct 14 '22 06:10

JodaStephen