简体   繁体   中英

Joda-Time DateTimeZone not comparing correctly

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.

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.

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