Search code examples
javadateparsingdatetimezoneddatetime

ZonedDateTime parse exception


I am trying to convert string to ZonedDateTime.

I have tried following:

SimpleDateFormat zonedDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");   
zonedDateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

long timeMs = zonedDateTimeFormat.parse("2017-07-18T20:26:28.582+03:00[Asia/Istanbul]").getTime();

It gives java.text.ParseException: Unparseable date

How can I parse the following string into ZonedDateTime

2017-07-18T20:26:28.582+03:00[Asia/Istanbul]

Solution

  • The java.time API has many inbuilt-formats that simplify parsing and formatting process. The String you are trying to parse is in the standard ISO_ZONED_DATE_TIME format. So, you could parse it easily in the following way and then get the milliseconds from the epoch:

    DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME ;
    ZonedDateTime zdt = ZonedDateTime.parse(
                            "2017-07-18T20:26:28.582+03:00[Asia/Istanbul]", 
                            formatter);  // prints 2017-07-18T20:26:28.582+03:00[Asia/Istanbul]
    long timeInMs = zdt.toInstant().toEpochMilli();