Search code examples
javajava-timedatetime-parsinglocaldatetimedatetimeformatter

What is wrong with this java date formatter?


I'm trying to format the date you see as a String in the below code, to be able to have it as a LocalDateTime object, but I'm getting an exception, I'm following this guide https://mkyong.com/java8/java-8-how-to-convert-string-to-localdate/, but unfortunately it doesn't have and example like the date I have below, can someone please give me a hand here? I would really appreciate :)

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE MMM d hh:mm:ss zzz yyyy",   Locale.US);
String date = "Wed Nov 18 00:00:00 COT 2020";
LocalDateTime localDateTime = LocalDateTime.parse(date, formatter);
System.out.println(localDateTime);
System.out.println(formatter.format(localDateTime));

I am getting:

java.time.format.DateTimeParseException: Text 'Wed Nov 18 00:00:00 COT 2020' could not be parsed at index 0


Solution

  • If you want round trip parsing/formatting with Zones try

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy",   Locale.US);
        String date = "Wed Nov 18 00:00:00 COT 2020";
        ZonedDateTime localDateTime = ZonedDateTime.parse(date, formatter);
        System.out.println(localDateTime);
        System.out.println(formatter.format(localDateTime));