2013-06-22 15 views
1

我想在单元测试中比较两个Joda日期的相等性。 expected使用new DateTime(...)创建,而parsed使用DateTimeFormatter从字符串中解析。Joda:如何比较同一时区中的不同时区表示的日期实例?

尽管我的日期字符串包含时区片段+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 

回答

1

刚刚找到自己的答案。有对DateTimeFormatter,防止它从解决时区偏移一个选项:

ISODateTimeFormat.dateTime().withOffsetParsed() 
+1

或者你可以既'DateTime'值转换为'Instant'值,并比较这些...但我怀疑,如果没有'withOffsetParsed'它可能完全忽略偏移量,如果字符串中的偏移量非常不同,则会得到错误的结果。 –

+0

当我仅比较时间戳时,只会比较实例。 04:00 + 02:00将等于02:00Z,这不是我所需要的。 –

+0

但它不会是02:00Z会吗?因为你会在两者中包含时区。说实话,在这一点上你确实期望得到的东西有点令人困惑。 –