For two Java OffsetDateTime objects of the same instant, but with different
timezone offset, to check whether they represent the same point in time,
the isEqual
method should be used.
var date1 = OffsetDateTime.parse("2008-12-03T11:00+01:00");
var date2 = OffsetDateTime.parse("2008-12-03T12:00+02:00");
date1.isEqual(date2); // the result is true
date1.equals(date2); // the result is false
date1.compareTo(date2); // the result < 0
In the above code, both of the OffsetDateTime objects represent “2008-12-03T10:00Z”.
However, the equals
or the compareTo
method will tell these two object are not “equal”.
The OffsetDateTime class uses a field of LocalDateTime and a field of ZoneOffset
to represent an instant. Its equals
method cares about whether all these field
of two objects are same or not. Obviously, fields of date1
are not equals with
ones of date2
.
The compareTo
has same behavior as equals
.
It is “consistent with equals”, as defined by Comparable.
As per Javadoc of OffsetDateTime, what isEqual
does is dateTime1.toInstant().equals(dateTime2.toInstant())
.
That is OffsetDateTime object are convert to Instant object first, and use
the equals
of Instant for comparison.
From the Javadoc of Instant,
An instantaneous point on the time-line.
the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, … The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z
An Instant object has no timezone info stored, only epoch of fixed UTC timezone stored, a long and a int.
Side note: what’s the different between ZonedDateTime and OffsetDateTime
The major difference is that ZonedDateTime knows Daylight saving time (DST), while OffsetDateTime does not. It’s because OffsetDateTime only stores simple offset to UTC, while ZonedDateTime stores much richer timezone info.