Home > Enterprise >  How can I parse a month and a year without a date in Java?
How can I parse a month and a year without a date in Java?

Time:05-04

I tried it like this

public LocalDate parseDate(String date) {
    return LocalDate.parse(date, DateTimeFormatter.ofPattern("MM-yyyy"));
}

but this code throw an exception

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, Year=2022},ISO of type java.time.format.Parsed

CodePudding user response:

YearMonth

You cannot create a LocalDate having a month of year and the year only, it just needs a day of month (and does not provide any default value).

Since you are trying to parse a String of the format "MM-uuuu", I assume you are not interested in creating a LocalDate, which inevitably boils down to the use of a java.time.YearMonth.

Example:

public static void main(String[] args) {
    // an arbitrary mont of year
    String strMay2022 = "05-2022";
    // prepare the formatter in order to parse it
    DateTimeFormatter ymDtf = DateTimeFormatter.ofPattern("MM-uuuu");
    // then parse it to a YearMonth
    YearMonth may2022 = YearMonth.parse(strMay2022, ymDtf);
    // if necessary, define the day of that YearMonth to get a LocalDate
    LocalDate may1st2022 = may2022.atDay(1);
    // print something meaningful concerning the topic…
    System.out.println(may1st2022   " is the first day of "   may2022);
}

Output:

2022-05-01 is the first day of 2022-05
  • Related