Home > Java > javaTutorial > 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
Release: 2024-11-04 11:16:29
Original
719 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template