1

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 3
    Based on my limited experimentation, the parser seems unwilling to attempt to parse the day (and probably the month) name values without more context, ie, which language it should use. I changed the formatter to `DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.UK)` and was able to get your code to work – MadProgrammer Sep 11 '18 at 00:09
  • 1
    If you could get a string with an offset of either `GMT` or `+0000` rather then `UTC`, it would conform with [`DateTimeFormatter.RFC_1123_DATE_TIME`](https://docs.oracle.com/javase/10/docs/api/java/time/format/DateTimeFormatter.html#RFC_1123_DATE_TIME). I realize it’s probably not an option for you, but wanted to mention it in case. – Ole V.V. Sep 11 '18 at 09:17

1 Answers1

7

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));
KCS
  • 442
  • 5
  • 20
Gatusko
  • 2,503
  • 1
  • 17
  • 25