Reputation: 79
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
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
There are two problems with your code:
YYYY
is for week-based year and only useful with a week number. Use either lower case yyyy
or uuuu
.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()
.Related questions:
uuuu
versus yyyy
in DateTimeFormatter
formatting pattern codes in Java?Upvotes: 2