【发布时间】:2020-01-19 03:12:04
【问题描述】:
我正在尝试用文字 'Z' 解析 ISO-8601 日期。
这将正确格式化日期:
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String string = formatter.format(OffsetDateTime.now());
System.out.println(string);
打印:
2020-01-19T03:06:58.090Z
然后,尝试立即将其读回:
TemporalAccessor acc = formatter.parse(string);
OffsetDateTime time = OffsetDateTime.from(acc);
System.out.println(time);
失败:
Exception in thread "main" java.time.DateTimeException: Unable to obtain OffsetDateTime from TemporalAccessor: {MinuteOfHour=6, MilliOfSecond=90, MicroOfSecond=90000, HourOfAmPm=3, NanoOfSecond=90000000, SecondOfMinute=58},ISO resolved to 2020-01-19 of type java.time.format.Parsed
at java.time.OffsetDateTime.from(OffsetDateTime.java:370)
at HelloWorld.main(HelloWorld.java:27)
Caused by: java.time.DateTimeException: Unable to obtain ZoneOffset from TemporalAccessor: {MinuteOfHour=6, MilliOfSecond=90, MicroOfSecond=90000, HourOfAmPm=3, NanoOfSecond=90000000, SecondOfMinute=58},ISO resolved to 2020-01-19 of type java.time.format.Parsed
at java.time.ZoneOffset.from(ZoneOffset.java:348)
at java.time.OffsetDateTime.from(OffsetDateTime.java:359)
... 1 more
我无法将模式更改为使用非文字'Z',但我注意到将其更改为Z,因此它可以成功读取末尾带有+0000 的日期。我也不能更改使用TemporalAccessor 读取日期,因为它来自第三方(杰克逊)。有什么想法吗?
【问题讨论】:
-
你为什么要将文字
Z附加到可能具有非 UTC 偏移量的OffsetDateTime上? -
如果您不控制输入、格式或代码,我们怎么可能提供帮助?
-
我希望以 UTC 显示日期。我不应该使用
OffsetDateTime吗?奇怪的是,当我打印System.out.println(OffsetDateTime.now());时,我最后得到了一个文字Z:2020-01-19T03:24:13.778Z。 -
@shmosel - 我控制格式,但由于客户端 API 要求,格式必须为
2020-01-19T03:24:13.778Z,而不是2020-01-19T03:24:13.778+0000。代码来自杰克逊,我试图弄清楚为什么它无法解析我的一个对象中的OffsetDateTimefield。我做了这个小例子来分享。 -
我的意思是模式字符串。
标签: java datetime java-8 jackson