如何在 Java 中解析没有日期的月份和年份?

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

我这样试过

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

但是这段代码抛出异常

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

YearMonth

您不能创建一个 LocalDate 只包含一年中的月份和年份,它只需要月份中的某一天(并且不提供任何默认值)。

由于您正在尝试解析 "MM-uuuu" 格式的 String,我假设您对创建 LocalDate 不感兴趣,这不可避免地归结为使用java.time.YearMonth.

示例:

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);
}

输出:

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