为什么 java8 中具有时区行为的 Instant.parse() 字符串与 java 17 不同

问题描述 投票:0回答:1

以下代码片段

Instant.parse("2023-08-08T00:00:00+02:00")

按照 java-17 中的预期编译和执行。但是用java-8执行时,抛出以下异常

java.time.format.DateTimeParseException: Text '2023-08-01T00:00:00+02:00' could not be parsed at index 19

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.Instant.parse(Instant.java:395)
    ...

我的问题是为什么? java.time api 有什么变化吗?

请注意,我确实知道解决此问题的方法,以下代码适用于 java-8

OffsetDateTime.parse("2023-08-01T00:00:00+02:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME).toInstant()

它产生了期望的结果。我有兴趣知道在 java-time api 实现中,行为是否已经改变?

java java-8 java-time timezone-offset java-17
1个回答
0
投票

此更改发生在 Java 12 中。版本 8 到 11 将抛出此异常,而从 12 开始的版本将接受时区偏移。

正如文档所述,

Instant.parse
方法使用
DateTimeFormatter.ISO_INSTANT
解析器。后者已在版本 1112 之间进行了更改(请参阅链接)。在版本12中,在ISO_INSTANT解析器的描述中添加了以下句子:

解析时,DateTimeFormatterBuilder.appendOffsetId() 的行为将用于解析偏移量,根据需要将即时转换为 UTC。

© www.soinside.com 2019 - 2024. All rights reserved.