xsd:dateTime 到 Java OffsetDateTime [英] xsd:dateTime to Java OffsetDateTime
问题描述
为了使用 JAXB 正确处理 xs:dateTime,我必须从 String
->java.time.OffsetDateTime
.
In order to properly handle an xs:dateTime with JAXB, I have to write my own converter from String
->java.time.OffsetDateTime
.
正如 XML Schema Definition 中提到的,dateTime 的灵感来自 ISO 8601.我使用 OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
来解析 xs:dateTime
,这适用于例如
As mentioned in the XML Schema Definition, dateTime was inspired by ISO 8601. I used OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
to parse the xs:dateTime
, which works fine for e.g.
"2007-12-03T10:15:30+01:00" //or
"2007-12-03T10:15:30Z"
遗憾的是,在 xs:dateTime
中偏移部分 被声明为可选,所以解析有效的
Sadly, in xs:dateTime
the offset part is declared optional, so parsing the valid
"2016-03-02T17:09:55"
抛出 DateTimeParseException
.
有没有DateTimeFormatter
用于 OffsetDateTime,它还处理未分区的 xs:dateTime
s(可能带有默认时区)?
Is there a DateTimeFormatter
for OffsetDateTime, which also handles unzoned xs:dateTime
s (probably with a default timezone)?
推荐答案
我认为没有内置的,但您可以在 DateTimeFormatterBuilder
类.
I don't think there's a built-in one but you can make your own with the help of the DateTimeFormatterBuilder
class.
您可以指定一个可选的偏移量,用方括号括起来,即[XXXXX]
(匹配"+HH:MM:ss"
),然后,您可以提供默认偏移量(parseDefaulting
) 在它不存在的情况下.如果要默认为UTC,可以设置0表示不指定偏移量;如果您想默认为 VM 的当前偏移量,您可以使用 OffsetDateTime.now().getLong(ChronoField.OFFSET_SECONDS)
获取它.
You can specify an optional offset enclosed in squared brackets, i.e. [XXXXX]
(to match "+HH:MM:ss"
), Then, you can provide a default offset (parseDefaulting
) in the case where it is not present. If you want to default to UTC, you can set 0 to specify no offset; and if you want to default to the current offset of the VM, you can get it with OffsetDateTime.now().getLong(ChronoField.OFFSET_SECONDS)
.
public static void main(String[] args) {
String[] dates = {
"2007-12-03T10:15:30+01:00",
"2007-12-03T10:15:30Z",
"2016-03-02T17:09:55",
"2016-03-02T17:09:55Z"
};
DateTimeFormatter formatter =
new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss[XXXXX]")
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
// or OffsetDateTime.now().getLong(ChronoField.OFFSET_SECONDS)
.toFormatter();
for (String date : dates) {
System.out.println(OffsetDateTime.parse(date, formatter));
}
}
这篇关于xsd:dateTime 到 Java OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!