LocalDate: MM-yyyy parsing

I get java.time.format.DateTimeParseExceptionafter trying to do the following:

LocalDate.parse( "09-2017" , DateTimeFormatter.ofPattern("MM-yyyy") )

What's wrong? Does Java have a utility for checking dateString formats?

+4
source share
2 answers

A LocalDateday, month and year is needed. Your input has only a month and a year. You will need to select an arbitrary day and install it in the analyzed object in order to create LocalDate.

You can either parse it on java.time.YearMonth, and then select the day:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-yyyy");
YearMonth ym = YearMonth.parse("09-2017", fmt);
LocalDate dt = ym.atDay(1); // choose whatever day you want

Or you can use java.time.format.DateTimeFormatterBuilderc java.time.temporal.ChronoFieldto determine the default value for the day:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // month-year
    .appendPattern("MM-yyyy")
    // default value for day
    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
    // create formatter
    .toFormatter();
LocalDate dt = LocalDate.parse("09-2017", fmt);

PS: , YearMonth ( ).

+13

/ localDate, ...

System.out.println(LocalDate.parse("01-09-2017", DateTimeFormatter.ofPattern("dd-MM-yyyy")));

.

-1

Source: https://habr.com/ru/post/1686043/


All Articles