Skip to content
Advertisement

Parse datetime with offset string to LocalDateTime

I am trying to parse following datetime String to LocalDateTimeObject, however I am not able to identify the format of the datetime string.

Sat, 09 Oct 2021 02:10:23 -0400

    String s = "Sat, 09 Oct 2021 02:10:23 -0400";
    DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    LocalDateTime dateTime = LocalDateTime.parse(s, formatter);
    System.out.println(dateTime);

How should I determine the pattern of the above string?

Advertisement

Answer

You should first check if the date string matches any of the Predefined Formatters.

If not, then you have to make your own Formatter using .ofPattern(String pattern) or .ofPattern(String pattern, Locale locale). To do this, you can see all the defined pattern letters here in section Patterns for Formatting and Parsing.

For your example, you can use either DateTimeFormatter.RFC_1123_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
OffsetDateTime dateTime = OffsetDateTime.parse(s, formatted);

or:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
OffsetDateTime dateTime = OffsetDateTime.parse(s, formatted);

Note that OffsetDateTime is used to represent the date-time with an offset from UTC.


 Symbol  Meaning       
 ------  -------        
   E     day-of-week 
   d     day-of-month
   M     month-of-year
   y     year-of-era
   H     hour-of-day (0-23)
   m     minute-of-hour
   s     second-of-minute
   Z     zone-offset
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement