简体   繁体   English

保留时区信息的ISO8601到DateTime

[英]ISO8601 to DateTime with time zone information preserved

Below is a deserialization of an ISO8601 date string that contains time zone information. 下面是包含时区信息的ISO8601日期字符串的反序列化。 Notice that the time zone information is lost: 请注意,时区信息丢失:

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

Time zone information (UTC offset) is serialized, as in +03:00 and +02:00 at the end of the ISO8601 strings, but it is lost after deserialization. 时区信息(UTC偏移)被序列化,如ISO8601字符串末尾的+ +03:00+02:00 ,但在反序列化后丢失。 As you can see the date2 DateTime object, which I expected to be a copy of date1 has the system's UTC offset instead of +02:00 , which date1 had. 正如你所看到的date2 DateTime对象,这是我预计的副本date1对系统的UTC偏移,而非+02:00 ,其中date1了。

How do I deserialize an ISO8601 string as to preserve the UTC offset? 如何反序列化ISO8601字符串以保留UTC偏移量?

The constructor you are using, new DateTime(Object instant) , (actually passed through to BaseDateTime ) doesn't parse , instead it converts the given object (in your case, a String ). 您正在使用的构造函数, new DateTime(Object instant) ,(实际传递给BaseDateTime )不会解析 ,而是转换给定的对象(在您的情况下,为String )。

Long story short, it uses the default time zone: 长话短说,它使用默认时区:

  1. The constructor considers the passed parameter an Instant and requests an InstantConverter from ConverterManager 构造函数将传递的参数视为Instant并从ConverterManager请求InstantConverter
  2. The constructor calls getInstantMillis() on that StringConverter 构造函数在StringConverter上调用getInstantMillis()
  3. That method actually does use a standard ISO 8601 DateTimeFormatter , however instead of parse it calls parseMillis() . 该方法实际上使用标准的ISO 8601 DateTimeFormatter ,但是不是parse 而是调用parseMillis()
  4. parseMillis , as you can see from the javadocs , returns a date in the default time zone . javadocs可以看到, parseMillis默认时区中返回一个日期。

Use DateTime.parse instead: 改为使用DateTime.parse

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM