Home > Java > javaTutorial > Why Does Parsing '2010-10-02T12:23:23Z' Throw 'Illegal pattern character 'T'' in Java's Date API?

Why Does Parsing '2010-10-02T12:23:23Z' Throw 'Illegal pattern character 'T'' in Java's Date API?

Linda Hamilton
Release: 2024-12-08 20:58:18
Original
626 people have browsed it

Why Does Parsing

Illegal Pattern Character 'T' while Parsing a Date String to java.util.Date

Question:

When attempting to parse a date string like "2010-10-02T12:23:23Z" using the Java Date API, an exception is thrown: "java.lang.IllegalArgumentException: Illegal pattern character 'T'". Why is this occurring, and is it necessary to manually split and parse the string?

Answer:

The 'T' character in the string, which represents the time separator, is the cause of the issue. To resolve this, it is necessary to escape the 'T' character with single quotes ('') in the pattern string. The correct pattern should be "yyyy-MM-dd'T'hh:mm:ssZ".

Example:

String date = "2010-10-02T12:23:23Z";
String pattern = "yyyy-MM-dd'T'hh:mm:ssZ";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
    Date d = sdf.parse(date);
    System.out.println(d.getYear());
} catch (ParseException e) {
    e.printStackTrace();
}
Copy after login

Alternatively, for Java 8 and higher, it is recommended to use Instant.parse instead, which provides a more robust and modern approach to parsing dates.

Instant.parse("2015-04-28T14:23:38.521Z")
Copy after login

The above is the detailed content of Why Does Parsing '2010-10-02T12:23:23Z' Throw 'Illegal pattern character 'T'' in Java's Date API?. 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