Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DateTimeFormatter's override zone work when parsing?

Tags:

java

java-time

I'm confused by the DateTimeFormatter's withZone method's behavior when it comes to parsing. According to it's documentation:

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.

Based on this and on the fact that DateTimeFormatter.ISO_DATE_TIME parses time zones, I'd expect the following two tests to pass.

@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));
}

But while the former does, the latter doesn't:

java.lang.AssertionError: Expected 2017-02-02T09:00Z[UTC], got 2017-02-02T09:00+01:00[UTC+01:00] instead.

So it seems that the override zone is used whether a time zone is found in the input or not. I've found the similar behavior mentioned briefly in this answer, when it's suggested that it might be a bug in JDK, but I haven't found a corresponding ticket on OpenJDK's bug tracker. Is it in fact a bug, or is my understanding of this documentation incorrect?

Update I've tested this with java version 1.8.0_121.

like image 837
korolar Avatar asked Feb 02 '17 10:02

korolar


1 Answers

This is a bug indeed, only not JDK-8033662, but rather JDK-8177021. It has been reported there that the assertion will fail for all Java 8 versions (I confirm that it fails with 1.8.0_172, the most recent one ATM), but pass with Java 9.

like image 193
adutra Avatar answered Nov 03 '22 07:11

adutra