我一直在为一个使用 Joda-Time 的项目进行单元测试,我注意到应该表示相同时区的 DateTimeZone
实例在 上没有返回 true等于
。特别是在像下面这样的单元测试中
// 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); }
即使 Africa/Lagos
和 GMT+01:00
是同一时区,并且两个 DateTimes
代表同一个瞬间 - 事实上,下面的两个测试证实了这一点
// 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
DateTimeZone
不相等:一个称为 Africa/Lagos
,另一个称为 GMT+01:00
。它在 the Javadoc of DateTimeZone.equals
中说
true if equal, based on the ID and all internal rules
对于DateTime.equals
:
Compares this object with the specified object for equality based on the millisecond instant, chronology and time zone.
时区不相等,因此 DateTime
也不相等。
也许它们实际上相等,并不意味着它们实际上相等。
请注意,java.util.TimeZone
具有 hasSameRules(...)
方法,该方法与相等性不同。
关于java - Joda-Time DateTimeZone 比较不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318268/