ISO8601至DateTime,并保留时区信息 [英] ISO8601 to DateTime with time zone information preserved
问题描述
以下是包含时区信息的ISO8601日期字符串的反序列化。请注意,时区信息丢失:
Below is a deserialization of an ISO8601 date string that contains time zone information. 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
时区信息(UTC偏移量)被序列化,如 +03:00
和 +02:00
的ISO8601字符串,但它在反序列化后丢失。可以看到 date2
DateTime对象,我预计这是一个 date1
的副本,具有系统的UTC偏移量 +02:00
,其中 date1
有。
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. 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.
如何反序列化ISO8601字符串以保留UTC偏移?
How do I deserialize an ISO8601 string as to preserve the UTC offset?
推荐答案
您正在使用的构造函数new DateTime(Object instant)
(实际传递给 BaseDateTime
)不解析,而是转换 em>给定的对象(在你的情况下,一个 String
)。
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
).
长篇小说,它使用默认时区:
Long story short, it uses the default time zone:
- 构造函数将传递的参数视为
Instant
并请求<来自 InstantConverter href =http://joda-time.sourceforge.net/apidocs/org/joda/time/convert/ConverterManager.html>ConverterManager
- 构造函数调用
getInstantMillis()
StringConverter
- 然而,该方法实际上使用了标准ISO 8601
DateTimeFormatter
而不是parse
电话parseMillis()
-
parseMillis
,您可以从 javadocs ,返回默认时区中的日期。
- The constructor considers the passed parameter an
Instant
and requests an InstantConverter fromConverterManager
- The constructor calls
getInstantMillis()
on thatStringConverter
- That method actually does use a standard ISO 8601
DateTimeFormatter
, however instead ofparse
it callsparseMillis()
. parseMillis
, as you can see from the javadocs, returns a date in the default time zone.
使用 DateTime.parse
代替:
DateTime date2 = DateTime.parse(date1.toString());
// 2013-09-22T19:21:48.461+02:00
这篇关于ISO8601至DateTime,并保留时区信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!