14

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

2
  • 1
    It's not a LocalDate because for that you need to specify a day. Which date should 201510 represent? The first of that month? Commented Dec 3, 2015 at 9:13
  • it works for me, compiled and run with jdk1.8.0_25 Commented Dec 3, 2015 at 9:15

2 Answers 2

27

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);
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.