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
Linda HamiltonOriginal
2024-12-08 20:58:18624browse

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();
}

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")

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!

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