Search code examples
javastringdatesimpledateformat

Parsing string to date: Illegal pattern character 'T'.


I need to parse a string to date in java. My string has the following format:

2014-09-17T12:00:44.0000000Z

but java throws the following exception when trying to parse such format... java.lang.IllegalArgumentException: Illegal pattern character 'T'.

Any ideas on how to parse that?

Thank you!


Solution

  • Given your input of 2014-09-17T12:00:44.0000000Z, it is not sufficient to escape the letter T only. You also have to handle the trailing Z. But be aware, this Z is NOT a literal, but has the meaning of UTC+00:00 timezone offset according to ISO-8601-standard. So escaping Z is NOT correct.

    SimpleDateFormat handles this special char Z by pattern symbol X. So the final solution looks like:

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX");
     Date d = sdf.parse("2014-09-17T12:00:44.0000000Z");
     System.out.println(d); // output: Wed Sep 17 14:00:44 CEST 2014
    

    Note that the different clock time is right for timezone CEST (toString() uses system timezone), and that the result is equivalent to UTC-time 12:00:44. Furthermore, I had to insert seven symbols S in order to correctly process your input which pretends to have precision down to 100ns (although Java pre 8 can only process milliseconds).