【问题标题】:Comparing two joda DateTime instances比较两个 joda DateTime 实例
【发布时间】:2014-01-18 18:17:03
【问题描述】:

我在比较两个 DateTime 对象时遇到问题。

System.out.println(response.getCreationDate().toString()); // will return "2013-12-31T22:59:21.000+01:00", but...

assertThat(response.getCreationDate(), equalTo(new DateTime("2013-12-31T22:59:21+01:00"))); // will throw an assertation error with the following error

Expected: <2013-12-31T22:59:21.000+01:00>
 but: was <2013-12-31T22:59:21.000+01:00>

有人知道我在这里缺少什么吗?

顺便说一句,如果您想知道为什么 DateTime 显示在 GMT+1:00 区域,因为这是我希望我的 DateTime 对象默认使用的时区。

谢谢!

【问题讨论】:

  • 尝试比较它们的毫秒值。调试会让你走得更远。
  • 是的,比较millis返回它们是相等的,但这也应该有效 - 对吧?
  • getCreationDate()返回的值是什么类型?
  • org.joda.time.DateTime
  • 你能用println(response.getCreationDate.getClass())确认吗?我没有发现其他任何问题。

标签: java datetime jodatime


【解决方案1】:

DateTimeAbstractInstant 继承其equals 方法。就是这样实现的

public boolean equals(Object readableInstant) {
    // must be to fulfil ReadableInstant contract
    if (this == readableInstant) {
        return true;
    }
    if (readableInstant instanceof ReadableInstant == false) {
        return false;
    }
    ReadableInstant otherInstant = (ReadableInstant) readableInstant;
    return
        getMillis() == otherInstant.getMillis() &&
        FieldUtils.equals(getChronology(), otherInstant.getChronology());
}

注意最后一行比较年表。您的实例的年表可能不同。

【讨论】:

  • 如果我提取两个日期时间对象的年表,我会得到以下信息:ISOChronology[+01:00] ISOChronology[Europe/Belgrade] 但贝尔格莱德是在 GMT+1:00。
  • @SpaseMarkovski 你去。年表不等于时区。
  • 它们不一样吗?欧洲/贝尔格莱德是格林威治标准时间+1:00。
  • @SpaseMarkovski 这不是Chronology 的唯一目的。
【解决方案2】:

此代码(示例):

    Chronology ch1 = GregorianChronology.getInstance();
    Chronology ch2 = ISOChronology.getInstance();

    DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);
    DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);

    System.out.println(dt);
    System.out.println(dt2);

    boolean b = dt.equals(dt2);

    System.out.println(b);

将打印:

2013-12-31T16:59:21.000-05:00
2013-12-31T16:59:21.000-05:00
false

您可能正在比较两个日期相同但Chronology 不同的DateTimes。

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多