Home >Java >javaTutorial >Why Does Parsing '2010-10-02T12:23:23Z' Throw 'Illegal pattern character 'T'' in Java's Date API?
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!