javadatetimejava-timedatetime-parsinglocaldatetime

Parse DateTime with DateTimeFormatter


I need to parse a date that I receive in a String with the following format: "Mon, 07 Nov 2022 21:00:00 +0100"

I have to dump the date to an object of type LocalDateTime and I use the following code:

String fecha = "Mon, 07 Nov 2022 21:00:00 +0100";
    
DateTimeFormatter formato = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss XXXX");    
LocalDateTime fechaHora = LocalDateTime.parse(fecha, formato);

but I get a DateTimeParseException. I can't find the error. Can you help me? Thank you


Solution

  • There is a pre-defined format for that: RFC_1123_DATE_TIME

    String fecha = "Mon, 07 Nov 2022 21:00:00 +0100";
        
    DateTimeFormatter formato = DateTimeFormatter.RFC_1123_DATE_TIME;    
    LocalDateTime fechaHora = LocalDateTime.parse(fecha, formato);