Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 836
Ye Wint Avatar asked Dec 03 '15 09:12

Ye Wint


2 Answers

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);
like image 171
Tunaki Avatar answered Nov 14 '22 14:11

Tunaki


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.

like image 33
assylias Avatar answered Nov 14 '22 14:11

assylias