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

How to Parse ISO 8601 String with Missing Colon in Offset in Java 8?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 08:19:02505browse

How to Parse ISO 8601 String with Missing Colon in Offset in Java 8?

Parsing ISO 8601 String without Colon in Offset to Java 8 Date

The issue arises when attempting to parse an ISO 8601-formatted string with an offset lacking a colon (e.g., "2018-02-13T10:20:12.120 0000") using the new date-time API in Java 8.

Solution

Until bug is fixed (Java 8)

Use a workround:

  • Hack: Insert colon in input string:
<code class="java">String input = "2018-02-13T10:20:12.120+0000".replace( "+0000" , "+00:00" );
OffsetDateTime odt = OffsetDateTime.parse( input );</code>
  • Explicit formatting pattern:
<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 bug is fixed:

To parse without workarounds:

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

Additional Notes:

  • Avoid legacy date-time classes like java.util.Date and SimpleDateFormat.
  • Use OffsetDateTime for offsets and Instant for UTC values.
  • For time zone conversion, use ZonedDateTime.
  • Review Stack Overflow for additional examples and information.

The above is the detailed content of How to Parse ISO 8601 String with Missing Colon in Offset in Java 8?. 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