Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to LocalDateTime in Java

I have this String

Fri, 07 Aug 2020 18:00:00 +0000

And I need to convert it to a LocalDateTime

I tryed several ways:

create a DateTimeFormatter and parse the String

String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss", Locale.getDefault());
LocalDateTime parsedDate = LocalDateTime.parse(publishedString, formatter);

Convert it to a Date with a SimpleDateFormat and then convert the resultDate to a LocalDateTime

String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date date = dateFormatter.parse(publishedString);
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

both solution gives me the same exception:

java.time.format.DateTimeParseException: Text 'Fri, 07 Aug 2020 18:00:00 +0000' could not be parsed 
at index 0 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)

How can I convert that String?

like image 958
Ivan Notarstefano Avatar asked Dec 05 '25 04:12

Ivan Notarstefano


2 Answers

tl;dr

OffsetDateTime.parse( 
    "Fri, 07 Aug 2020 18:00:00 +0000" , 
    DateTimeFormatter.RFC_1123_DATE_TIME 
)

See this code run live at IdeOne.com.

LocalDateTime is the wrong class

Your input string contains +0000 which indicates an offset-from-UTC.

So you should not be using LocalDateTime. That class purposely lacks any concept of time zone or offset. With LocalDateTime, your string Fri, 07 Aug 2020 18:00:00 +0000 will become 6M on August 7th 2020, but we won't know if that is 6 PM in Tokyo Japan, 6 PM in Toulouse France, or 6 PM in Toledo Ohio US — all different moments several hours apart.

OffsetDateTime

Instead, this value should be parsed as OffsetDateTime.

Parsing

Your input's format is that of RFC 1123. That particular format is predefined in java.time.

String input = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter f = DateTimeFormatter.RFC_1123_DATE_TIME;
OffsetDateTime odt = OffsetDateTime.parse( input , f );

odt.toString(): 2020-08-07T18:00Z

like image 175
Basil Bourque Avatar answered Dec 06 '25 18:12

Basil Bourque


I'd say use Locale.ROOT and don't forget the Z in the DateTimeFormatter class

String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss Z", Locale.ROOT);
LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter);
like image 23
ItsLhun Avatar answered Dec 06 '25 18:12

ItsLhun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!