作者:心忆泪痕 | 来源:互联网 | 2023-02-05 15:53
我正在努力确保调用toString()
我的ZonedDateTime
Object符合ISO-8601格式.
该toString()
方法的文档说明:
...如果偏移和ID相同,则输出与ISO-8601兼容
这是否意味着存在一种情况,即呼叫
zdt.getOffset()
会返回不同的东西
zdt.getZone().getRules().getOffset(zdt.toInstant())
?
这似乎没有意义.
有人可以提供偏移和ID不相同的示例(即:toString()
不符合ISO-8601的地方),以便我可以更好地理解文档中的描述.
谢谢.
1> JodaStephen..:
这是完整的规范:
* Outputs this date-time as a {@code String}, such as
* {@code 2007-12-03T10:15:30+01:00[Europe/Paris]}.
*
* 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
,因此offset和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
可以看出,在第二种情况下,ZoneOffset
使用a,toString()
格式省略了末尾的方括号部分.通过省略该部分,结果与ISO-8601兼容.
boolean iso8601Compatible = zdt.getZone() instanceof ZoneOffset;
要保证ISO-8601兼容输出,请使用toOffsetDateTime()
:
String isoCompatible = zdt.toOffsetDateTime().toString();
或格式化程序.
"或格式化程序":[DateTimeFormatter.ISO_OFFSET_DATE_TIME](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME)让人想起.
2> Ole V.V...:
文档中的示例为2007-12-03T10:15:30+01:00[Europe/Paris]
。由于ISO-8601不包含该[Europe/Paris]
零件,因此这不符合ISO要求。java.time
开发人员添加了此功能,这是在尽可能接近标准的合理性与仍然以明确方式提供时区信息之间的折衷。
所以真正的问题可能实际上是相反的:如果ZonedDateTime.toString()
包括时区信息ISO不包括,当是结果完全符合ISO标准?“如果偏移量和ID相同”是什么意思?在这里,我们必须记住,它ZoneOffset
是中的子类,ZoneID
可以用作中的区域ID ZonedDateTime
。在这种情况下,偏移量和ID相同。否则他们不是。对于特定示例,ZonedDateTime.now(ZoneOffset.ofHours(+2)).toString()
可能会产生2017-04-26T15:04:59.828+02:00
。这是完全与ISO兼容的,因为区域指定为just +02:00
,与偏移量相同。还ZonedDateTime.now(ZoneOffset.UTC).toString()
给出了格式2017-04-26T13:04:59.828Z
。由于Z
算作偏移量,因此也兼容。
我认为在大多数情况下,它不是很有用。如果您的区域只是一个偏移量,通常会首选使用OffsetDateTime
over ZonedDateTime
,如果这样,那么您当然不在乎ZonedDateTime.toString()
ISO 是否兼容。