Android God
Android God

Reputation: 79

String Month-Year 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("MMMM-YYYY"))
                            .toFormatter(Locale.ENGLISH);

LocalDate KFilter = LocalDate.parse("August-2021", formatter);

The error log is

java.time.format.DateTimeParseException: Text 'August-2021' could not be parsed: 
Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2021, MonthOfYear=8},
ISO of type java.time.format.Parsed

Can you please help me out on the same ?

Upvotes: 2

Views: 1648

Answers (1)

Anonymous
Anonymous

Reputation: 86148

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(DateTimeFormatter.ofPattern("MMMM-uuuu"))
            .toFormatter(Locale.ENGLISH);

    LocalDate kFilter = YearMonth.parse("August-2021", formatter).atDay(1);

    System.out.println(kFilter);

Output:

2021-08-01

What went wrong in your code?

There are two problems with your code:

  1. Format pattern strings are case sensitive. Upper case YYYY is for week-based year and only useful with a week number. Use either lower case yyyy or uuuu.
  2. Month and year do not define a date, so you cannot readily parse them into a LocalDate. I suggest you parse into a YearMonth and then convert. In the conversion you need to decise on a day of month. An alternative would be specifying a day of month through DateTimeFormatterBuilder.parseDefaulting().

Links

Related questions:

Upvotes: 2

Related Questions