Rudziankoŭ
Rudziankoŭ

Reputation: 11251

LocalDate: parse MM-yyyy

I get java.time.format.DateTimeParseException after attempt to do following:

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

What is wrong? Is there any utility in Java to check dateString formats?

Upvotes: 11

Views: 10105

Answers (1)

user7605325
user7605325

Reputation:

A LocalDate needs the day, month and year to be built. Your input has only the month and year. You'll have to choose an arbitrary day and set it to the parsed object to create a LocalDate.

You can either parse it to a java.time.YearMonth, and then choose 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 a java.time.format.DateTimeFormatterBuilder with a java.time.temporal.ChronoField to define a 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: If you just want to check if the input is correct, just parsing it to a YearMonth is enough (it already checks if the parsed values are valid).

Upvotes: 31

Related Questions