Home > Java > javaTutorial > How to Parse ISO 8601 Dates with \'Z\' Literal Using SimpleDateFormat?

How to Parse ISO 8601 Dates with \'Z\' Literal Using SimpleDateFormat?

Susan Sarandon
Release: 2024-11-04 01:46:30
Original
430 people have browsed it

How to Parse ISO 8601 Dates with 'Z' Literal Using SimpleDateFormat?

Parsing ISO 8601 Dates with 'Z' Literal in SimpleDateFormat

Question:

How to parse an ISO 8601 date that includes the "Z" literal, indicating UTC time, using Java's SimpleDateFormat?

Issue:

Using common date patterns like "yyyy-MM-dd'T'HH:mm:ss" or "yyyy-MM-dd'T'HH:mm:ssz" with SimpleDateFormat results in incorrect parsing. The "Z" literal, representing UTC time, is not being recognized.

Answer:

To parse ISO 8601 dates with the "Z" literal using SimpleDateFormat, you can use the following pattern:

<code class="java">yyyy-MM-dd'T'HH:mm:ssX</code>
Copy after login

Explanation:

The "X" specifier in the pattern represents the UTC time zone offset in the ISO 8601 format. It can be used to parse dates with the "Z" literal, which indicates a zero offset from UTC.

Example:

<code class="java">SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = sdf.parse("2010-04-05T17:16:00Z");

System.out.println(date);
// Output: Sun Apr 05 17:16:00 UTC 2010</code>
Copy after login

The above is the detailed content of How to Parse ISO 8601 Dates with 'Z' Literal Using SimpleDateFormat?. 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