Alberto
Alberto

Reputation: 359

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

Upvotes: 0

Views: 443

Answers (2)

Savi
Savi

Reputation: 1

Your code is working fine in my local.

However if you want to convert a string to date you can also use SimpleDateFormat

For Ex:

String sDate1="Mon, 07 Nov 2022 21:00:00 +0100";  
Date date1=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ssZ").parse(sDate1);  
System.out.println(date1); 

Upvotes: 0

Christoph Dahlen
Christoph Dahlen

Reputation: 836

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);

Upvotes: 2

Related Questions