0

I have a problem. I've tried to parse a String which contains a date into another DateFormat. Code:

String datumString = "Mon, 27 Jan 2020 21:31:16 +0100";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
    Date zeitstempel = null;
    try {
        zeitstempel = simpleDateFormat.parse(datumString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(zeitstempel);

Error message:

java.text.ParseException: Unparseable date: "Mon, 27 Jan 2020 21:31:16 +0100"
at java.text.DateFormat.parse(DateFormat.java:366)
at de.puki.geopolitan.Main.<init>(Main.java:32)
at de.puki.geopolitan.Main.main(Main.java:73)

Please help. :)

  • 1
    Why you have only one d in parse format ? – kulatamicuda Jan 28 '20 at 18:46
  • `EEE, d MMM` --> `EEE, dd MMM` – brso05 Jan 28 '20 at 18:47
  • String datumString = "EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ"; – Marwen Jaffel Jan 28 '20 at 18:47
  • I copy and pasted your code and it works without error for me. Are you sure that error is referencing the code you posted? –  Jan 28 '20 at 18:48
  • 2
    @jhell If the code works or not depends if you are on an system with English or non-English locale. – Robert Jan 28 '20 at 18:59
  • @Robert good find. I am English locale. –  Jan 28 '20 at 19:07
  • 1
    please use the java-8 date time api https://stackoverflow.com/questions/58830202/java-date-time-conversion-to-given-timezone/58830241#58830241 – Ryuzaki L Jan 28 '20 at 19:22
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `OffsetDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jan 28 '20 at 22:00
  • The formatter you need is built in. `OffsetDateTime.parse(datumString, DateTimeFormatter.RFC_1123_DATE_TIME)` yeidls `2020-01-27T21:31:16+01:00`. No need to fiddle with a format pattern string and a locale yourself. – Ole V.V. Jan 28 '20 at 22:05

1 Answers1

4

The variable names show that you are German, most likely working on a system with German language and date formatting. By default this also affects SimpleDateFormat output and parsing (unless you specify the Locale to be used)!

Between the German and the English/US formatted date string there is a small but significant difference:

Locale.ENGLISH: "Mon, 27 Jan 2020 21:31:16 +0100";
Locale.GERMAN:  "Mo., 27 Jan 2020 21:31:16 +0100";

The date string you parse however uses the English date format, therefore you have to explicitly set Locale.US or Locale.ENGLISHwhen constructing the SimpleDateFormat:

simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);

Afterwards you can parse the sample date string in your question.

Robert
  • 39,162
  • 17
  • 99
  • 152