Month Year In String to Local Date

Viewed 72

I am trying to parse some date-string into a date value, however, using the below code, I am getting an exception:

My Code

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
          .parseCaseInsensitive()
          .append(DateTimeFormatter.ofPattern("MMM-uuuu"))
          .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
          .toFormatter(Locale.ENGLISH);

         LocalDate KFilter = null;
         KFilter = YearMonth.parse("July-2021", formatter).atDay(1)

The error log is

java.time.format.DateTimeParseException: Text 'July-2021' could not be parsed at index 3
3 Answers

I think the format is the problem : "MMM-uuuu" isn't compatible with the string "july" so at the index 3 'y' it was expecting the '-'

The format should match. Try this.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("MMM-uuuu"))
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .toFormatter(Locale.ENGLISH);
    
    LocalDate KFilter = null;
    KFilter = YearMonth.parse("Jul-2021", formatter).atDay(1);

Use Jul-2021 instead of July-2021

LocalDate KFilter = null;
         KFilter = YearMonth.parse("Jul-2021", formatter).atDay(1)
Related