Search code examples
javajava-8localdate

Month Year In String to Local Date


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

Solution

  • 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);