Search code examples
javadatesimpledateformatiso8601

Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java


I am trying to parse a String using SimpleDateFormat.

This is my current code:

public String getCreatedDateTime() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddEHH:mm:ss.zzzz");
    try {
        Date date = simpleDateFormat.parse("2015-06-27T13:16:37.363Z");
        return date.toString();
    } catch (ParseException e) {
        return "Error parsing date";
    }
}

As you can see, I just put a constant in the parse() method for testing purposes.

So, this is what I am trying to parse:

2015-06-27T13:16:37.363Z

This is the SimpleDateFormat pattern that I am using:

yyyy-MM-ddEHH:mm:ss.zzzz

I keep getting the ParseException.

I know that it is proably because of the .zzzz at the end but I have no idea what .363Z might stand for so I just used some random letters. Bad idea.

I'll appreciate your help a lot. Thank you!


Solution

  • Try with this pattern (note the X at the end and the 'T' in the middle):

    "yyyy-MM-dd'T'HH:mm:ss.SSSX"
    

    From Java's SimpleDateFormat's documentation:

    ISO 8601 Time zone:

    ...

    For parsing, "Z" is parsed as the UTC time zone designator.

    And, from the part where it describes the different characters:

    X - Time zone - ISO 8601 time zone

    EDIT

    If using Android, then "X" is not supported.

    You can use this pattern (note Z is a literal now):

    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    

    But then you'll get the date on your current timezone and would need to convert it to UTC if needed.