2

Im having issue with formatting this string into ZonedDateTime object. I tried following oracle docs but I failed and I have no idea how it should be.

String date = "Sat Dec 01 20:56:28 CET 2018"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu");
ZonedDateTime dateTime = ZonedDateTime.parse(date, formatter);

I get

java.time.format.DateTimeParseException: Text 'Sat Dec 01 20:56:28 CET 2018' could not be parsed at index 0

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • java.time.format.DateTimeParseException: Text 'Sat Dec 01 20:56:28 CET 2018' could not be parsed at index 0 – Paveli Tripo Dec 01 '18 at 20:52
  • By the way, this is a terrible format. Where possible, use the standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formats to exchange date-time values. The standard formats are used by default in the *java.time* classes when parsing/generating strings. – Basil Bourque Dec 01 '18 at 22:35
  • It looks like you are parsing the string from `toString()` from an old-fashioned `Date` object? If within your reach, rather use `Date.toInstant()` for converting to a modern type since it is easier and safer. Parsing the three letter time zone abbreviation robably works when it’s `CET` but will give wrong results in many other cases. – Ole V.V. Dec 01 '18 at 23:33

1 Answers1

2

Specify a Locale, to determine the human language used in translating name of month and such.

String date = "Sat Dec 01 20:56:28 CET 2018";
DateTimeFormatter formatter = 
    DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z uuuu" , 
        Locale.US 
    )
;

ZonedDateTime dateTime = ZonedDateTime.parse(date, formatter);
System.out.println(dateTime);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Lho Ben
  • 2,053
  • 18
  • 35