2013-09-22 47 views
5

下面是一个包含时区信息的ISO8601日期字符串的反序列化。请注意,时区信息丢失:ISO8601到日期时间保留时区信息

scala> val date1 = new DateTime().withZone(DateTimeZone.forID("Europe/Berlin")) 
date1: org.joda.time.DateTime = 2013-09-22T18:42:15.348+02:00 

scala> date1.getZone() 
res45: org.joda.time.DateTimeZone = Europe/Berlin 

scala> val date2 = new DateTime(date1.toString()) 
date2: org.joda.time.DateTime = 2013-09-22T19:42:15.348+03:00 

scala> date2.getZone() 
res46: org.joda.time.DateTimeZone = Europe/Vilnius 

scala> date1.getZone() == date2.getZone() 
res47: Boolean = false 

时区信息(UTC偏移)是序列化,如+03:00+02:00在ISO8601字符串的结束,但反序列化后丢失。正如你所看到的DateTime对象,我预计将是date1的副本具有系统的UTC偏移量而不是+02:00,其中date1有。

如何反序列化ISO8601字符串以保留UTC偏移量?

回答

7

您正在使用的构造,new DateTime(Object instant),(通过实际传递给BaseDateTime)不解析,而是转换给定对象(在你的情况下,String)。

长话短说,它使用默认时区:

  1. 构造认为传递的参数的Instant并请求InstantConverterConverterManager
  2. 构造函数调用上StringConverter
  3. 这种方法getInstantMillis()实际上确实使用标准ISO 8601 DateTimeFormatter,但不是parseit calls parseMillis()
  4. parseMillis,如您从javadocs所见,返回默认时区中的日期。

使用DateTime.parse代替:

DateTime date2 = DateTime.parse(date1.toString()); 
// 2013-09-22T19:21:48.461+02:00 
+0

辉煌!我已经找到了一种使用'ISODateTimeFormat.dateTimeParser()。withOffsetParsed()。parseDateTime(dateTimeString)'的方法,但是这样做更好。干杯。 –

+0

@DominykasMostauskis太棒了!我花了最后20分钟解析代码,并用解释更新了我的答案。知道它为什么会这样工作总是很好的。希望这可以帮助。不要忘记upvote,如果它帮助:) – Nicole

+0

+1,你一定会赢得它;) –

相关问题