Java 8 Time API: how to parse string of format “MM.yyyy” to LocalDate

岁酱吖の 提交于 2019-12-03 00:55:08

It makes sense: your input is not really a date because it does not have a day information. You should parse it as a YearMonth and use that result 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 need to apply a specific day, you can obtain a LocalDate from a YearMonth for example:

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

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

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

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

Following alternative is probably not so nice but at least a successfully tested solution, too, so I mention it here for completeness and as supplement to the right 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!