java - DateTimeFormatter 的覆盖区域在解析时如何工作?

标签 java java-time

我对 DateTimeFormatterwithZone 方法在解析时的行为感到困惑。根据它的文档:

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/

相关文章:

java - @RequestBody 注释在 Spring 中不起作用并给出 NoSuchMethodError 错误

java - 在Java中创建具有多个子节点的XML文件

java - 无法从基于周的字符串的 TemporalAccessor 获取 LocalDate

java-8 - 使用 DateTimeFormatter 将字符串解析为 ZonedDateTime

datetime - 使用 Java 8 到天花板的圆形分钟

java - DOM getElementsByTagName() 返回具有 NULL 值的节点

Linux 上的 Java 套接字错误(发送 0xFF,接收到 -3)

java - 创建一个信任库以仅验证由 JAVA 中的自定义 CA 签名的证书

java - 如何使用java8设置工作日

java - 为任意 DatePicker 创建自定义年表