我对 DateTimeFormatter
的 withZone
方法在解析时的行为感到困惑。根据它的文档:
When parsing, there are two distinct cases to consider. If a zone has been parsed directly from the text, perhaps because DateTimeFormatterBuilder.appendZoneId() was used, then this override zone has no effect. If no zone has been parsed, then this override zone will be included in the result of the parse where it can be used to build instants and date-times.
基于此以及 DateTimeFormatter.ISO_DATE_TIME
解析时区这一事实,我希望以下两个测试能够通过。
@Test
public void testNoZoneInInput() {
final ZonedDateTime expected = ZonedDateTime.of(2017, 2, 2, 9, 0, 0, 0, ZoneId.of("UTC"));
final ZonedDateTime actual = ZonedDateTime.parse("2017-02-02T10:00:00", DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("UTC+1")));
Assert.assertTrue("Expected " + expected + ", got " + actual + " instead.", expected.isEqual(actual));
}
@Test
public void testWithZoneInInput() {
final ZonedDateTime expected = ZonedDateTime.of(2017, 2, 2, 9, 0, 0, 0, ZoneId.of("UTC"));
final ZonedDateTime actual = ZonedDateTime.parse("2017-02-02T09:00:00Z", DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("UTC+1")));
Assert.assertTrue("Expected " + expected + ", got " + actual + " instead.", expected.isEqual(actual));
}
但是前者有,后者没有:
java.lang.AssertionError: Expected 2017-02-02T09:00Z[UTC], got 2017-02-02T09:00+01:00[UTC+01:00] instead.
因此,无论在输入中是否找到时区,似乎都会使用覆盖区域。我在 this answer 中发现了类似的行为,当它提示它可能是 JDK 中的错误时,但我还没有在 OpenJDK 的错误跟踪器上找到相应的票证。这实际上是一个错误,还是我对本文档的理解不正确?
更新 我已经使用 Java 版本 1.8.0_121 对此进行了测试。
最佳答案
这确实是一个错误,只是不是 JDK-8033662,而是 JDK-8177021 .据报道,所有 Java 8 版本的断言都会失败(我确认它在 1.8.0_172 上失败,这是最新的一个 ATM),但在 Java 9 上通过。
关于java - DateTimeFormatter 的覆盖区域在解析时如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999421/