本文介绍了ZonedDateTime toString与ISO 8601的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to ensure that calling toString() on my ZonedDateTime Object will comply with ISO-8601 format.

toString()方法的文档指出:

这是否意味着存在呼叫的情况zdt.getOffset()将返回与zdt.getZone().getRules().getOffset(zdt.toInstant())?

Does this mean that there exists a situation where callingzdt.getOffset()will return something different thanzdt.getZone().getRules().getOffset(zdt.toInstant())?

这似乎没有道理.

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

Can someone provide an example in which the offset and ID are not the same (ie: where toString() does not comply with ISO-8601) so that I can better understand the description in the documentation.

推荐答案

这是完整的规范:

 * 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规范是指使用ZoneOffset而不是用命名的ZoneId构造ZonedDateTime的情况,因此,偏移量和ID相同:

The Javadoc specification refers to the case where the ZonedDateTime is constructed with a ZoneOffset rather than a named ZoneId, thus where the offset and ID are the same:

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

可以看出,在第二种情况下,使用ZoneOffset时,toString()格式在末尾省略了方括号部分.省略该部分,结果是与ISO-8601兼容.

As can be seen, in the second case, where a ZoneOffset is used, the toString() format omits the square bracket section at the end. By omitting that section, the result is ISO-8601 compatible.

boolean iso8601Compatible = zdt.getZone() instanceof ZoneOffset;

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

To guarantee an ISO-8601 compatible output use toOffsetDateTime():

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

或格式化程序.

这篇关于ZonedDateTime toString与ISO 8601的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:46