java.text.ParseException: Unparseable date "yyyy-MM-dd'T'HH:mm:ss.SSSZ" - SimpleDateFormat

71,919

Solution 1

Z represents the timezone character. It needs to be quoted:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

Solution 2

In Java 7 you can also use the X pattern to match an ISO8601 timezone, which includes the special Z (UTC) value:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX");
Date date = sdf.parse("2007-09-25T15:40:51.0000000Z");

However, it seems to require an exact number of millisecond characters in the pattern, which is not required for the 'Z' character pattern, and is rather inconvenient. I think this is because the ISO8601 definition also includes "two-digit hours", which are just numbers, so cannot be distinguished by the parser from the preceding milliseconds.

So this version would be fine for timestamps down to second precision, less so for milliseconds.

Share:
71,919
Jacob
Author by

Jacob

Hi :) .. avoid this for your life quality ;) https://www.linkedin.com/in/kozlowskijakub

Updated on December 04, 2021

Comments

  • Jacob
    Jacob over 2 years

    I would appreciate any help with finding bug for this exception:

    java.text.ParseException: Unparseable date: "2007-09-25T15:40:51.0000000Z"
    

    and following code:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    Date date = sdf.parse(timeValue);
    long mills = date.getTime();
    this.point.time = String.valueOf(mills);
    

    It throws expcetion with Date date = sdf.parse(timeValue); .

    timeValue = "2007-09-25T15:40:51.0000000Z"; , as in exception.

    Thanks.

  • DNA
    DNA over 10 years
    Or possibly use X instead of Z so that Z is accepted as an ISO8601 timezone, for which "Z" is parsed as the UTC time zone designator
  • DNA
    DNA over 10 years
    Using X works for me, BUT seems to require an exact number of S (millisecond) characters in the patterns, which is strange - see my answer...
  • Reimeus
    Reimeus over 10 years
    It's in the javadoc Text can be quoted using single quotes (') to avoid interpretation
  • IgorGanapolsky
    IgorGanapolsky over 8 years
    IllegalArgumentException: Unknown pattern character 'X'
  • IgorGanapolsky
    IgorGanapolsky over 8 years
    @Reimeus This solution didn't work for me. I tried the 'Z', and it didn't get parsed. It only worked when I removed the Z.
  • DNA
    DNA over 8 years
    Igor - what version of Java gives that error? The 'X' pattern is clearly documented for Java 7, and works for me under Java 8 too.
  • IgorGanapolsky
    IgorGanapolsky over 8 years
    I am using ThreeTenABP library in my Android project (Java 8).
  • Reimeus
    Reimeus over 8 years
    @IgorGanapolsky sounds like you need to post a new question will full details of your code & environment
  • Ole V.V.
    Ole V.V. over 2 years
    @IgorGanapolsky See my answer (works with ThreeTenABP too).