Home  >  Article  >  Java  >  How to Parse an ISO 8601 String with a Missing Colon in the Offset to Java 8 Date?

How to Parse an ISO 8601 String with a Missing Colon in the Offset to Java 8 Date?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 11:16:29680browse

How to Parse an ISO 8601 String with a Missing Colon in the Offset to Java 8 Date?

Parsing an ISO 8601 String with a Missing Colon in Offset to Java 8 Date

Problem:

Java 8's ZonedDateTime.parse() method fails to parse a date string in ISO 8601 format that lacks a colon in the offset, such as "2018-02-13T10:20:12.120 0000."

Solution:

Until the bug is fixed (Java 8 through 121):

Use a DateTimeFormatter with a customized pattern to specify the missing colon in the offset:

<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>

When the bug is fixed:

Simply call OffsetDateTime.parse() with the ISO 8601 string without a pattern:

<code class="java">OffsetDateTime odt = OffsetDateTime.parse("2018-02-13T10:20:12.120+0000");</code>

Details:

  • The OffsetDateTime class represents a date with an offset from UTC, which is appropriate for the input string.
  • By default, java.time uses ISO 8601 formats for parsing, but it expects a colon in the offset.
  • The DateTimeFormatter allows for customization, enabling you to specify the presence of the colon.
  • To avoid ambiguity, it's recommended to use the colon in offsets, always provide both hours and minutes (even if zero), and pad zero to the left of a single-digit minute.

The above is the detailed content of How to Parse an ISO 8601 String with a Missing Colon in the Offset to Java 8 Date?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn