簡體   English   中英

保留時區信息的ISO8601到DateTime

[英]ISO8601 to DateTime with time zone information preserved

下面是包含時區信息的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 ,其中date1了。

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

您正在使用的構造函數, new DateTime(Object instant) ,(實際傳遞給BaseDateTime )不會解析 ,而是轉換給定的對象(在您的情況下,為String )。

長話短說,它使用默認時區:

  1. 構造函數將傳遞的參數視為Instant並從ConverterManager請求InstantConverter
  2. 構造函數在StringConverter上調用getInstantMillis()
  3. 該方法實際上使用標准的ISO 8601 DateTimeFormatter ,但是不是parse 而是調用parseMillis()
  4. javadocs可以看到, parseMillis默認時區中返回一個日期。

改為使用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