Home > Enterprise >  Parse datetime with offset string to LocalDateTime
Parse datetime with offset string to LocalDateTime

Time:10-09

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?

CodePudding user response:

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 the following:

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

Note that ZonedDateTime is used to represent the date-time with a time-zone.


 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
  • Related