DateTimeParseException: Text could not be parsed at index 2 [duplicate]

三世轮回 提交于 2020-11-28 03:31:26

问题


I am really confused now why the following snippet results in DateTimeParseException.

public static void main(String[] args) {
        java.time.format.DateTimeFormatter dtf = java.time.format.DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz");
        String date = "Mon, 10 Sep 2018 23:57:09 UTC";
        System.out.println(dtf.parse(date));
}

The following exception is thrown:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon, 10 Sep 2018 23:57:09 UTC' could not be parsed at index 2
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)
    at com.sample.binding.bitronvideo.driver.BitronVideoRecordingDriver.main(BitronVideoRecordingDriver.java:448)

I would really appreciate further help.

Thanks, Amit


回答1:


I didn't get the exception. So Checking your profile I saw that your locale is in Germany so i tried this and got the exception.

    java.time.format.DateTimeFormatter dtf = 
             java.time.format.DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", 
                                                       Locale.GERMANY);
    String date = "Mon, 10 Sep 2018 23:57:09 UTC";
    System.out.println(dtf.parse(date));

And the shordays for German are :

Short weekdays So, Mo, Di, Mi, Do, Fr, Sa

Try with this code and I bet it will work

    java.time.format.DateTimeFormatter dtf =
              java.time.format.DateTimeFormatter.ofPattern("EE, dd MMM yyyy HH:mm:ss zzz");
    String date = "Mo, 10 Sep 2018 23:57:09 UTC";
    System.out.println(dtf.parse(date));

But for your String Date to work just use UK or US Locale by passing an argument

    java.time.format.DateTimeFormatter dtf =
           java.time.format.DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", 
                                                         Locale.UK);
    String date = "Mon, 10 Sep 2018 23:57:09 UTC";
    System.out.println(dtf.parse(date));


来源:https://stackoverflow.com/questions/52266975/datetimeparseexception-text-could-not-be-parsed-at-index-2

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