2011-01-07 60 views
13

我有两个时间戳,它们以两种不同的格式描述相同的时间。Joda与时区的分析日期

2010-10-03 18:58:072010-10-03T16:58:07.000+02:00

我用两个不同的日期格式化器与Joda解析时间戳。最后,我希望有两个DateTime对象在相同的时刻相同。

DateFormatter提供了几种方法来控制时区和地区,但我无法让它工作。

这是我想工作的代码:

final String date1 = "2010-10-03 18:58:07"; // Europe/Berlin local time 
    final DateTimeFormatter formatter1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
    final DateTime dateTime1 = formatter1.parseDateTime(date1); 

    final String date2 = "2010-10-03T16:58:07.000+02:00"; // Europe/Berlin local time with time zone 
    final DateTimeFormatter formatter2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
    final DateTime dateTime2 = formatter2.parseDateTime(date2); 

    Assert.assertTrue(dateTime1.isEqual(dateTime2)); 

在此先感谢如果有人能帮助我!

回答

6

如果您的默认时间zome是欧洲/柏林,2010-10-03 18:58:07对应于2010-10-03T16:58:07.000 + 00:00。

您可能会误解字符串表示中的时区字段。您的时间戳2010-10-03T16:58:07.000 + 02:00意味着“在距格林威治标准时间+2小时的时区为16:58:07”或其他措词“现在是16 :58:07在柏林”我假设你预计它意味着它是16点58分07秒GMT

+0

“2010-10-03T16:58:07.000 + 02:00”表示不是GMT时间为+2小时的时区不是16:58:07)“。它必须是:“2010-10-03T16:58:07.000 + 02:00表示在UTC时间偏移+2小时的时区为16:58:07)” – MicSim 2011-01-07 13:37:39

4

你两个时间戳并不代表在同一​​时刻(如jambjo已经说过)查看Time zone as offsets from UTC?维基百科上。

也看到它是如何工作的parseDateTime文档。如果不提供任何时区,则默认时区将应用(也就是柏林时区UTC + 2,如果你在那里)。所以:

  • 2010-10-03 18:58:07变为2010-10-03T18:58:07.000+02:00(18:58在柏林,与UTC的偏移为2小时,即UTC的16:58)如预期。
  • 2010-10-03T16:58:07.000+02:00停留,因为它是,因为没有提供一个时间段(即在柏林与16:58抵消2小时UTC,这意味着在14:58 UTC)

希望你有这个想法。您需要使用withZone方法调整时间以获得理想的结果。