Reputation: 12463
I've been working on unit tests for a project that uses Joda-Time, and I noticed that DateTimeZone
instances that should represent the same time-zone aren't returning true on equals
. In particular, on unit tests like these below
// should be the same
DateTimeZone WAT = DateTimeZone.forOffsetHours(1); // GMT+01:00
DateTimeZone LAG = DateTimeZone.forID("Africa/Lagos"); // Lagos
DateTime sample = new DateTime(2017, 11, 15, 10, 50);
DateTime dtzWAT = sample.withZoneRetainFields(WAT);
DateTime dtzLAG = sample.withZoneRetainFields(LAG);
@Test public void compareZones() { assertEquals(WAT, LAG); }
@Test public void compareTimes() { assertEquals(dtzWAT, dtzLAG); }
both tests fail even though Africa/Lagos
and GMT+01:00
are the same time zone, and the two DateTimes
represent the same instant - in fact, the two tests below confirm this
// both succeed
@Test public void compareStrings() {
assertEquals(dtzWAT.toString(), dtzLAG.toString());
}
@Test public void checkSameTime() {
assertFalse(dtzLAG.isBefore(dtzWAT));
assertFalse(dtzWAT.isBefore(dtzLAG));
}
Why does this happen? Why are the two time-zone instances not equivalent, and is there anyway around this? Any help would be appreciated.
Upvotes: 1
Views: 359
Reputation: 140299
why does this happen
The DateTimeZone
s are not equal: one is called Africa/Lagos
, the other is GMT+01:00
. It says in the Javadoc of DateTimeZone.equals
true if equal, based on the ID and all internal rules
And for DateTime.equals
:
Compares this object with the specified object for equality based on the millisecond instant, chronology and time zone.
The time zones aren't equal, so the DateTime
s aren't equal.
Maybe they are effectively equal, doesn't mean they actually are.
Note that java.util.TimeZone
has the hasSameRules(...)
method, which is a separate notion from equality.
Upvotes: 2