java - Joda-Time DateTimeZone 比较不正确

标签 java timezone jodatime

我一直在为一个使用 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/LagosGMT+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/

相关文章:

java - Spring @Value 注解无法解析

java - 如果你想访问encodeHexString等,你在哪里添加 'commons-codec-1.4.jar'?

java - 如果 url 页面为空,则返回另一个字符串

java - 如何创建其中包含列表的类,并且该列表应包含两种不同类型的对象

c - 应用程序运行时时间函数是否处理时区更改

python - 如何从 django 模型 DateTimeField 获取本地日期时间?

postgresql - Postgres 9.6,时区 : why are those two queries giving me different times

java - 按给定的 DateTimeFieldType 舍入 DateTime

java - 如何仅从月份和年份构造 LocalDateTime

java - 字符串到本地日期错误