解析时,我对DateTimeFormatter' withZone方法的行为感到困惑。根据它的文档:
解析时,要考虑两种不同的情况。如果直接从文本中解析了区域,则可能是因为使用了DateTimeFormatterBuilder.appendZoneId(),所以此覆盖区域无效。如果没有解析任何区域,则该覆盖区域将包含在解析结果中,可在该结果中用于构建瞬间和日期时间。
基于此以及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));
}
Run Code Online (Sandbox Code Playgroud)
但是,尽管前者做到了,但后者却没有:
java.lang.AssertionError:预期为2017-02-02T09:00Z [UTC],而是得到2017-02-02T09:00 + 01:00 [UTC + 01:00]。
因此,无论是否在输入中找到时区,似乎都使用了覆盖区。当我发现这可能是JDK中的错误时,我已经找到了在此答案中简要提到的类似行为,但是我在OpenJDK的错误跟踪器中未找到相应的故障单。实际上是错误,还是我对本文档的理解不正确?
更新 我已经用Java版本1.8.0_121对此进行了测试。
这确实是一个错误,只是不是 JDK-8033662 ,而是JDK-8177021。据报道,所有 Java 8 版本的断言都会失败(我确认最新的 ATM 1.8.0_172 会失败),但 Java 9 会通过。
| 归档时间: |
|
| 查看次数: |
188 次 |
| 最近记录: |