[ACCEPTED]-Java 8 Time API: how to parse string of format "MM.yyyy" to LocalDate-java-time

Accepted answer
Score: 65

It makes sense: your input is not really 7 a date because it does not have a day information. You 6 should parse it as a YearMonth and use that result 5 if you don't care about the day.

String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
YearMonth ym = YearMonth.parse(date, formatter);

If you do 4 need to apply a specific day, you can obtain 3 a LocalDate from a YearMonth for example:

LocalDate ld = ym.atDay(1);
//or
LocalDate ld = ym.atEndOfMonth();

You can also use 2 a TemporalAdjuster, for example, for the last day of the 1 month*:

LocalDate ld = ym.atDay(1).with(lastDayOfMonth());

*with an import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

Score: 17

Following alternative is probably not so 4 nice but at least a successfully tested 3 solution, too, so I mention it here for 2 completeness and as supplement to the right 1 answer of @assylias:

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseDefaulting(ChronoField.DAY_OF_MONTH, 1);
builder.append(DateTimeFormatter.ofPattern("MM.yyyy"));
DateTimeFormatter dtf = builder.toFormatter();

String ym = "04.2013";
LocalDate date = LocalDate.parse(ym, dtf);
System.out.println(date); // output: 2013-04-01

More Related questions