5

下面是包含时区信息的 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 偏移量)被序列化,在 ISO8601 字符串中+03:00+02:00结尾处,但在反序列化后会丢失。正如您所看到的date2,我希望作为副本的 DateTime 对象date1具有系统的 UTC 偏移量+02:00,而不是具有系统的 UTC 偏移量date1

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

4

1 回答 1

7

您正在使用的构造函数new DateTime(Object instant), (实际上是通过 to BaseDateTime)不会parse,而是转换给定的对象(在您的情况下是 a String)。

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

  1. 构造函数考虑传递的参数 an并Instant请求一个InstantConverterConverterManager
  2. 构造函数调用getInstantMillis()StringConverter
  3. 该方法实际上确实使用了标准 ISO 8601 DateTimeFormatter,但是parse 它没有调用parseMillis().
  4. parseMillis,正如您从javadocs中看到的那样,返回默认时区中的日期。

改用DateTime.parse

DateTime date2 = DateTime.parse(date1.toString());
// 2013-09-22T19:21:48.461+02:00
于 2013-09-22T17:23:23.390 回答