Search code examples
javadatetimesimpledateformatparseexception

How to format the String "2016-03-23T11:23:11.305+01:00" with SimpleDateFormat


How can I convert the String "2016-03-23T11:23:11.305+01:00" into a date?

I already tried the following, but I get a ParseException.

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

Solution

  • From the javadoc of SimpleDateFormat

    z = Time zone General time zone Pacific Standard Time; PST; GMT-08:00

    Z = Time zone RFC 822 time zone -0800

    X = Time zone ISO 8601 time zone -08; -0800; -08:00 Pattern letters are usually repeated, as their number determines the exact presentation:

    you should define the SimpleDateFormat with a X for the timezone to represent it for the ISO 8601 as.

    String d = "2016-03-23T11:23:11.305+01:00";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    Date da = df.parse(d);
    

    Also taken from the example in this doc

    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" = 2001-07-04T12:08:56.235-07:00