如何将“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: Text '2021-11-20+01:00' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2021-11-20 of type java.time.format.Parsed
...Unsupported field: 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。
最佳答案
不存在仅由日期和时区组成的 Java 类型。正如其名称所暗示的,ZonedDateTime 和 OffsetDateTime 包含日期和时间。因此,您需要创建一个格式化程序来假定一天中的默认时间:
String value = "2021-11-20+01:00";
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.appendPattern("yyyy-MM-ddxxx");
builder.parseDefaulting(ChronoField.HOUR_OF_DAY, 0);
DateTimeFormatter formatter = builder.toFormatter();
ZonedDateTime zDate = ZonedDateTime.parse(value, formatter);
当然,一天中的小时可以是您选择的任何值:例如,12
代表中午。但它必须是有效的。
关于java - 如何将 "2021-11-20+01:00"格式的日期字符串解析为 ZonedDateTime - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70049260/