Parsing Date Strings with Illegal Character
When attempting to parse a date string in Java using SimpleDateFormat, you may encounter the exception "Illegal pattern character 'T'". This issue arises when the date string contains a 'T' character, which designates the time component when following the ISO 8601 standard.
Cause of the Exception
The SimpleDateFormat class interprets 'T' as a special character that separates the date and time portions of the string. However, the default pattern does not include 'T' as a character, leading to the exception.
Possible Solutions
There are several ways to address this issue:
Modify the Pattern:
Use DateTimeFormatter (Java 8 ):
Example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"); Date date = formatter.parse("2010-10-02T12:23:23Z", LocalDateTime::from);
Manual String Splitting:
Note:
If the date string contains a trailing 'Z' to denote UTC time, ensure that the 'XXX' part of the pattern is included.
Improved Code Sample (with escaped 'T'):
public static void main(String[] args) { String date = "2010-10-02T12:23:23Z"; String pattern = "yyyy-MM-dd'T'hh:mm:ssXXX"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { Date d = sdf.parse(date); System.out.println(d.getYear()); } catch (ParseException e) { e.printStackTrace(); } }
The above is the detailed content of How to Handle 'Illegal pattern character 'T'' When Parsing Dates in Java?. For more information, please follow other related articles on the PHP Chinese website!