Cliff Pereira
Cliff Pereira

Reputation: 463

Parsing "Fri, 02 Dec 2016 12:29:00 +0100" to OffsetDateTime in Java

I'm kind of stuck when trying to parse the following string in Java

Fri, 02 Dec 2016 12:29:00 +0100

My approach using the OffsetDateTime was the following:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss xx");
OffsetDateTime time = OffsetDateTime.parse(dateString, formatter);

where "dateString" is the string obove. Am I missing something?

Thanks for your answers.

Upvotes: 1

Views: 247

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338496

Use predefined formatter

The DateTimeFormatter class provides a constant instance for that input string. That string format is defined by RFC 1123. Use the constant DateTimeFormatter.RFC_1123_DATE_TIME.

String input = "Fri, 02 Dec 2016 12:29:00 +0100";
OffsetDateTime odt = OffsetDateTime.parse ( input , DateTimeFormatter.RFC_1123_DATE_TIME );

odt.toString(): 2016-12-02T12:29+01:00

See live code in IdeOne.com.

English seems to be built into this formatter. Your JVM’s current default Locale is irrelevant. Adding a line such as Locale.setDefault ( Locale.CANADA_FRENCH ); to the above code has no impact. So, while the comments above give good advice to always specify a Locale rather than rely implicitly on the current default, this particular formatter is an exception.

Upvotes: 1

Related Questions