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

后端 未结 2 1193
面向向阳花
面向向阳花 2020-12-14 13:53

I\'m a bit discouraged with parsing dates in Java 8 Time API.

Previously I could easily write:

String date = \"04.2013\";
DateFormat df = ne         


        
2条回答
  •  长情又很酷
    2020-12-14 14:46

    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;

提交回复
热议问题