Not able to parse UTC date time to EST local time [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-12 02:13:41

问题


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.


回答1:


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'");



回答2:


It is because that the millisecond part of the time is absent from your input:

"2016-09-09T03:00:29Z" 
                    ^ unmatched place

You can either revise the input by adding the missing part(2016-09-09T03:00:29.000Z) or change your format pattern accordingly(yyyy-MM-dd'T'HH:mm:ss'Z').

Also, there's a typo in your output format (the minute part of the time):

"yyyy-MM-dd HH:MI:SS"

It should be replaced with yyyy-MM-dd HH:mm:ss.



来源:https://stackoverflow.com/questions/39403270/not-able-to-parse-utc-date-time-to-est-local-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!