Home > Java > javaTutorial > How to Handle 'Illegal pattern character 'T'' When Parsing Dates in Java?

How to Handle 'Illegal pattern character 'T'' When Parsing Dates in Java?

Patricia Arquette
Release: 2024-12-08 00:27:10
Original
962 people have browsed it

How to Handle

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:

  1. Modify the Pattern:

    • Add a single quote on both sides of 'T' in the pattern string. This escapes the character, allowing it to be interpreted as a literal.
    • Example: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ")
  2. Use DateTimeFormatter (Java 8 ):

    • Start using the modern DateTimeFormatter class introduced in Java 8.
    • Create a formatter with appropriate date and time patterns.
    • Example:

       DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
       Date date = formatter.parse("2010-10-02T12:23:23Z", LocalDateTime::from);
      Copy after login
  3. Manual String Splitting:

    • If the above approaches do not work, consider splitting the date string manually and parsing the date and time components separately.

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

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!

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