When attempting to parse an ISO 8601-formatted string ("2018-02-13T10:20:12.120 0000") using Java 8's ZonedDateTime class and a pre-defined format pattern, users may encounter a parsing error due to a missing colon in the offset.
This parsing issue stems from a bug in Java 8 that prevents the OffsetDateTime class from correctly parsing offsets without a colon between the hours and minutes. This bug affects offsets like " 0000" but not " 00:00".
Alter the input string to add the missing colon before parsing:
<code class="java">String input = "2018-02-13T10:20:12.120+0000".replace("+0000", "+00:00"); OffsetDateTime odt = OffsetDateTime.parse(input);</code>
Define a DateTimeFormatter with a specific pattern to guide the parsing:
<code class="java">String input = "2018-02-13T10:20:12.120+0000"; DateTimeFormatter f = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX"); OffsetDateTime odt = OffsetDateTime.parse(input, f);</code>
For a more adaptable formatting pattern, utilize a DateTimeFormatterBuilder:
<code class="java">DateTimeFormatter f = DateTimeFormatterBuilder.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX") .appendOffset("+HH:MM", "Z") .toFormatter(); OffsetDateTime odt = OffsetDateTime.parse(input, f);</code>
To simplify parsing, ensure that offsets always include a colon, include both hours and minutes (even if zero), and use padding zeros (-05:00 instead of -5).
<code class="java">Instant instant = odt.toInstant();</code>
<code class="java">ZoneId z = ZoneId.of("America/Montreal"); ZonedDateTime zdt = odt.atZoneSameInstant(z);</code>
The above is the detailed content of Why is Java 8\'s OffsetDateTime class struggling to parse ISO 8601 strings with offsets like \" 0000\"?. For more information, please follow other related articles on the PHP Chinese website!