1

I get a dateformat from wicket which Java can't convert:

Mon Apr 20 00:00:00 CEST 2020

The problem is that CEST is not a timezone Java supports. I've tried CST what should work but it doesn't. Error is:

Unparseable date: "Mon Apr 20 00:00:00 CST 2020"

Code:

DateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd", Locale.GERMANY);
dateFormat.parse("Mon Apr 20 00:00:00 CST 2020");
System.out.println(dateFormat.format(new Date()));

I need to convert this date in a JSON-Format so yyyy-MM-dd.

How can I do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • What code are you using to do the conversion? Please add it to your question by way of an edit (a code formatting tool is provided). – halfer Apr 20 '20 at 17:18
  • i added the code –  Apr 20 '20 at 17:52
  • 1
    I recommend you don’t use `DateFormat`, `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 20 '20 at 17:57
  • Really? You're asking why pattern `"yyyy-MM-dd"` can't parse text `"Mon Apr 20 00:00:00 CST 2020"`. Do they look even remotely similar? Text `"2020-04-20"` would fit that pattern. – Andreas Apr 20 '20 at 18:10

1 Answers1

3

This works for me:

        String dateStr = "Mon Apr 20 00:00:00 CEST 2020";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d H:mm:ss zzz yyyy", Locale.ENGLISH);
        ZonedDateTime parsedDate = ZonedDateTime.parse(dateStr, formatter);
        System.out.println(parsedDate);
        System.out.println(parsedDate.format(DateTimeFormatter.ISO_LOCAL_DATE));

The output from the above is: 2020-04-20T00:00+02:00[Europe/Paris] and 2020-04-20

I think the trick is that you need a formatter to parse this date because it's a pretty strange format using the year at the end of the string with the hours/minutes/seconds in between that and the rest of the date. Default date/time parsing isn't going to work.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • Wow it works for me too. Thanks a lot! –  Apr 20 '20 at 17:57
  • 2
    Your second formatting pattern is predefined in `DateTimeFormatter` as constant [`ISO_LOCAL_DATE`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE). So no need to define pattern `yyyy-MM-dd". – Basil Bourque Apr 20 '20 at 23:13