【问题标题】:Joda: How to compare date instances in same time zone with different time zone representations?Joda:如何将同一时区中的日期实例与不同时区表示进行比较?
【发布时间】:2013-06-22 17:24:37
【问题描述】:

我试图在我的单元测试中比较两个 Joda 日期是否相等。 expected 是使用 new DateTime(...) 创建的,而 parsed 是从带有 DateTimeFormatter 的字符串中解析出来的。

虽然我的日期字符串包含时区片段+02:00,但解析的日期具有时区Europe/Berlin。这在语义上是正确的(至少在 DST 期间),但是这两个日期不是 equal

当然,我可以使用DateTimeZone.forID("Europe/Berlin") 创建我预期的时区,但恕我直言,这并不完全正确。 Europe/Berlin 在冬季具有 +01:00 的偏移量,在夏季具有 +02:00 的偏移量。输入字符串明确指出+02:00,因此如果输入日期是在冬季,我的单元测试将失败。

关于如何解决这个问题的任何想法?

示例代码

DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
DateTime expected = new DateTime(2013, 6, 22, 11, 7, 22, 123, DateTimeZone.forOffsetHours(2));
String input = "2013-06-22T11:07:22.123+02:00";
DateTime parsed = formatter.parseDateTime(input);
System.out.println("expected: " + expected + " (" + expected.getChronology() + ")");
System.out.println("parsed  : " + parsed + " (" + parsed.getChronology() + ")");
System.out.println("equal   : " + expected.equals(parsed));

示例输出

expected: 2013-06-22T11:07:22.123+02:00 (ISOChronology[+02:00])
parsed  : 2013-06-22T11:07:22.123+02:00 (ISOChronology[Europe/Berlin])
equal   : false

【问题讨论】:

    标签: jodatime


    【解决方案1】:

    我自己找到了答案。 DateTimeFormatter 有一个选项可以防止它解析时区偏移:

    ISODateTimeFormat.dateTime().withOffsetParsed()
    

    【讨论】:

    • 或者您可以将两个 DateTime 值转换为 Instant 值并比较它们...但我怀疑如果没有 withOffsetParsed 它可能会完全忽略偏移量,您会得到如果字符串中的偏移量非常不同,则会出现错误的结果。
    • 当我只比较时间戳时,只会比较实例。 04:00+02:00 等于 02:00Z,这不是我需要的。
    • 但不会是 02:00Z 吧?因为您会在两者中都包含时区。老实说,您现在正在期待什么有点令人困惑。
    • 我正在编写测试,我不仅想断言我的被测对象(假设解析器)返回正确的瞬间(其中04:00+02:0002:00Z 将是相同的) 但它在当前时区返回正确的时间戳。
    • 但是 timestamps 本身并不是分区的。如果它真的是“当某事发生时”,那么这只是一个瞬间,我认为将其视为有一个时区是一个坏主意。这取决于您将如何使用它,但是当时间戳被视为时间瞬间时,生活会变得简单得多——首先,有一个明显的排序顺序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多