【发布时间】:2021-12-31 01:53:54
【问题描述】:
如何将“2021-11-20+01:00”格式化日期解析为ZonedDateTime?我正在尝试:
String value = "2021-11-20+01:00";
ZonedDateTime zDate = ZonedDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-ddxxx"));
但是得到这个奇怪的错误:
java.time.format.DateTimeParseException: 文本 '2021-11-20+01:00' 可能 无法解析:无法从 TemporalAccessor 获取 ZonedDateTime: {OffsetSeconds=3600},ISO解析为2021-11-20类型 java.time.format.Parsed
...不支持的字段:InstantSeconds...
有什么建议吗? European VIES VAT ID checking system 在接收 XML (SOAP) 响应时使用此时间格式:<requestDate>2021-11-20+01:00</requestDate>。 OffsetDateTime.. 出现同样的错误。
有趣的是,Javadoc 说“三个字母 (x) 输出小时和分钟,并带有冒号,例如 '+01:30'”。那么为什么上述模式不起作用?
也试过这个 - 同样的错误:
ZonedDateTime zDate = ZonedDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE);
完整的错误日志:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2021-11-20 +01:00' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2021-11-20 of type java.time.format.Parsed
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:402)
at javaapplication5.JavaApplication5.checkVATatVIES(JavaApplication5.java:162)
at javaapplication5.JavaApplication5.main(JavaApplication5.java:65)
Caused by: java.time.DateTimeException: Unable to obtain OffsetDateTime from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2021-11-20 of type java.time.format.Parsed
at java.base/java.time.OffsetDateTime.from(OffsetDateTime.java:370)
at java.base/java.time.format.Parsed.query(Parsed.java:235)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
... 3 more
Caused by: java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2021-11-20 of type java.time.format.Parsed
at java.base/java.time.Instant.from(Instant.java:378)
at java.base/java.time.OffsetDateTime.from(OffsetDateTime.java:365)
... 5 more
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
at java.base/java.time.format.Parsed.getLong(Parsed.java:203)
at java.base/java.time.Instant.from(Instant.java:373)
... 6 more
使用 OpenJDK 11。
【问题讨论】:
-
根据定义,LocalDateTime 是没有定义偏移量的日期和时间。您可能想使用 OffsetDateTime 而不是 LocalDateTime。
-
那个字符串的时间是多少?
-
没有使用时间,只是日期 2021-11-20,格林威治标准时间 +1 小时。
-
更新的问题 - 问题仍然存在..
-
我在这些投票后修改了问题,所以我希望接近投票将被撤回。
标签: java parsing localdatetime datetimeformatter