Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatter could not be parsed using "HH:mm E d MMM YYYY" pattern

I am retrieving a date/time from an external data source, this is returned in the following format "14:30 Sat 05 May" with no year.

I've been trying to parse this to a LocalDateTime unsuccessfully. The data returned does not return a year as it is an assumption that we are always operating in the current year.

//date to parse
String time = "14:30 Sat 05 May";

//specify date format matching above string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm E d MMM YYYY") ;

//we do not have a year returned but i can make the assumption we use the current year
LocalDateTime formatDateTime = LocalDateTime.parse(time, formatter).withYear(2018);

The above code throws the following exception

Exception in thread "main" java.time.format.DateTimeParseException: Text '14:30 Sat 05 May' could not be parsed at index 16

Any help appreciated.

like image 784
RoRo88 Avatar asked Mar 06 '23 06:03

RoRo88


1 Answers

Default year

Specify a default year in your DateTimeFormatter, using the DateTimeFormatterBuilder class by calling parseDefaulting and specifying the year-field with ChronoField.YEAR.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("HH:mm E d MMM")
    .parseDefaulting(ChronoField.YEAR, 2018)  // <------
    .toFormatter(Locale.ENGLISH);

With this formatter instead of yours:

LocalDateTime.parse( "14:30 Sat 05 May" , formatter ) 

…I get:

2018-05-05T14:30

See that code run live at IdeOne.com.

Points to note:

  • Your format pattern string needs to match the parsed string end-to-end. So when your date-time string doesn’t have a year in it, don’t include YYYY in your format pattern.
  • In any case don’t use uppercase YYYY here. It’s for week-based year and only useful with week numbers. If your string had had a year in it, you should have used uuuu or lowercase yyyy.
  • Make it a habit to give explicit locale to your formatter so you know it also works on other computers, and on yours when one day you play with its settings.
like image 182
Ole V.V. Avatar answered Mar 19 '23 21:03

Ole V.V.