Home > Java > javaTutorial > 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
Release: 2024-11-03 08:19:02
Original
556 people have browsed it

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

When bug is fixed:

To parse without workarounds:

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

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!

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