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
,它还处理未分区的 xs:dateTime
s(可能带有默认时区)?
Is there a DateTimeFormatter
for OffsetDateTime, which also handles unzoned xs:dateTime
s (probably with a default timezone)?
推荐答案
我认为没有内置的,但你可以在 DateTimeFormatterBuilder
class。
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屋!