ISO8601 到 DateTime,并保留时区信息

2024-04-11

下面是包含时区信息的 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 and +02:00位于 ISO8601 字符串的末尾,但反序列化后会丢失。正如你所看到的date2DateTime 对象,我希望它是其副本date1有系统的 UTC 偏移量而不是+02:00, which date1 had.

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


您正在使用的构造函数,new DateTime(Object instant) http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#DateTime%28java.lang.Object%29,(实际上传递到BaseDateTime)不parse,取而代之的是converts给定的对象(在你的情况下,一个String).

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

  1. 构造函数将传递的参数视为Instant并要求即时转换器 http://joda-time.sourceforge.net/apidocs/org/joda/time/convert/InstantConverter.html from ConverterManager http://joda-time.sourceforge.net/apidocs/org/joda/time/convert/ConverterManager.html
  2. 构造函数调用getInstantMillis() http://grepcode.com/file/repo1.maven.org/maven2/joda-time/joda-time/2.0/org/joda/time/convert/StringConverter.java#StringConverter.getInstantMillis%28java.lang.Object%2Corg.joda.time.Chronology%29在那StringConverter
  3. 该方法实际上使用了标准 ISO 8601DateTimeFormatter,但是而不是parse 它调用parseMillis() http://grepcode.com/file/repo1.maven.org/maven2/joda-time/joda-time/2.0/org/joda/time/convert/StringConverter.java#StringConverter.getInstantMillis%28java.lang.Object%2Corg.joda.time.Chronology%29.
  4. parseMillis,正如你可以看到的javadocs http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormatter.html#parseMillis%28java.lang.String%29,返回一个日期默认时区.

Use DateTime.parse反而:

DateTime date2 = DateTime.parse(date1.toString());
// 2013-09-22T19:21:48.461+02:00
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ISO8601 到 DateTime,并保留时区信息 的相关文章

随机推荐