Parsing ISO 8601 Dates with SimpleDateFormat and 'Z' Literal
Problem:
Attempting to parse an ISO 8601 date string containing the "Z" timezone literal using the SimpleDateFormat class with various patterns fails to return the correct UTC time. Specifically, the date "2010-04-05T17:16:00Z" is parsed as "Mon Apr 05 17:16:00 EDT 2010", despite the "Z" literal indicating UTC.
Solution:
The SimpleDateFormat class is unable to handle timestamps in ISO 8601 format by default. However, in Java 7, a new pattern was introduced to specifically handle this situation:
yyyy-MM-dd'T'HH:mm:ssX
This pattern expects the "X" timezone suffix, which can represent a "Z" literal to indicate UTC. When using this pattern, SimpleDateFormat correctly parses the date to its UTC equivalent.
Alternative Date Parser:
If SimpleDateFormat does not meet your needs, you can also consider using alternative date parsing libraries such as Joda-Time or ThreeTen-Backport, which have better support for ISO 8601 dates and timezone literals.
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!