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

Ana*_*y K 4 java parsing date

我尝试过这样的

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

但这段代码抛出异常

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, Year=2022},ISO of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud)

deH*_*aar 7

YearMonth

\n

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

\n

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

\n

例子:

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

输出:

\n
2022-05-01 is the first day of 2022-05\n
Run Code Online (Sandbox Code Playgroud)\n