user2325154 user2325154 - 2 months ago 5
Java Question

Not able to parse UTC date time to EST local time

Getting following exception while parsing UTC date time to EST local time.

Exception:

Stacktrace:] with root cause
java.text.ParseException: Unparseable date: "2016-09-09T03:00:29Z"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.study.crud.util.GenericUtils.convertUTCDateToEST(GenericUtils.java:55)


GenericUtils.java

public static String convertUTCDateToEST(String utcDate) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
inFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date aDate = inFormat.parse(utcDate);

DateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:MI:SS");
outFormat.setTimeZone(TimeZone.getTimeZone("EST"));
String estDate = outFormat.format(aDate);

return estDate;
}


Found some similar stuff on SO here java.text.ParseException: Unparseable date "yyyy-MM-dd'T'HH:mm:ss.SSSZ" - SimpleDateFormat and tried solutions proposed there but did not work.

Answer

There is a error in the input format. You have specified milli seconds as an input to your format .SSS and then the zone Z.

You have however not passed the milli second option. The following format works

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