Ye Wint
Ye Wint

Reputation: 879

Why my pattern("yyyyMM") cannot parse with DateTimeFormatter (java 8)

When I using SimpleDateFormat, it can parse.

SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
format.setLenient(false);
Date d = format.parse(date);

But When I use Java 8 DateTimeFormatter,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = LocalDate.parse(date, formatter);

it throws

java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java .time.format.Parsed

String value for date is "201510".

Upvotes: 14

Views: 14887

Answers (2)

assylias
assylias

Reputation: 328735

You can use a YearMonth and specify the day you want (say the first for example):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = YearMonth.parse(date, formatter).atDay(1);

Or if the day is irrelevant, just use a YearMonth.

Upvotes: 6

Tunaki
Tunaki

Reputation: 137184

Ask yourself the question: which day should be parsed with the String "201510"? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed.

If you just want to parse a year and a month, you can use the YearMonth object instead:

YearMonth localDate = YearMonth.parse(date, formatter);

However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                .appendPattern("yyyyMM")
                                .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                                .toFormatter();
LocalDate localDate = LocalDate.parse(date, formatter);

Upvotes: 27

Related Questions