gpt4 book ai didi

java - ZonedDateTime toString 与 ISO 8601 的兼容性

转载 作者:太空狗 更新时间:2023-10-29 22:50:22 29 4
gpt4 key购买 nike

我试图确保在我的 ZonedDateTime 对象上调用 toString() 将符合 ISO-8601 格式。

toString() 方法的文档指出:

...The output is compatible with ISO-8601 if the offset and ID are the same

这是否意味着存在调用zdt.getOffset()将返回不同于zdt.getZone().getRules().getOffset(zdt.toInstant())

这似乎没有意义。

有人可以提供一个偏移量和 ID 不相同的示例吗(即:toString() 不符合 ISO-8601 的地方)以便我更好地理解中的描述文档。

最佳答案

这是完整的规范:

 * Outputs this date-time as a {@code String}, such as
* {@code 2007-12-03T10:15:30+01:00[Europe/Paris]}.
* <p>
* The format consists of the {@code LocalDateTime} followed by the {@code ZoneOffset}.
* If the {@code ZoneId} is not the same as the offset, then the ID is output.
* The output is compatible with ISO-8601 if the offset and ID are the same.

Javadoc 规范指的是 ZonedDateTime 是用 ZoneOffset 而不是命名的 ZoneId 构造的情况,因此偏移量和ID相同:

System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Paris")));
// 2017-04-26T15:13:12.006+02:00[Europe/Paris]

System.out.println(ZonedDateTime.now(ZoneOffset.ofHours(2)));
// 2017-04-26T15:13:12.016+02:00

可以看出,在第二种情况下,使用了 ZoneOffsettoString() 格式省略了末尾的方括号部分。通过省略该部分,结果与 ISO-8601 兼容。

boolean iso8601Compatible = zdt.getZone() instanceof ZoneOffset;

要保证 ISO-8601 兼容输出,请使用 toOffsetDateTime():

String isoCompatible = zdt.toOffsetDateTime().toString();

或格式化程序。

关于java - ZonedDateTime toString 与 ISO 8601 的兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634226/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com