我尝试过这样的
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)
YearMonth您不能创建一个LocalDate仅具有一年中的月份和年份的值,它只需要月份中的一天(并且不提供任何默认值)。
由于您正在尝试解析 aString格式"MM-uuuu",我假设您对创建 a 不感兴趣LocalDate,这不可避免地归结为 a 的使用java.time.YearMonth。
例子:
\npublic 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}\nRun Code Online (Sandbox Code Playgroud)\n输出:
\n2022-05-01 is the first day of 2022-05\nRun Code Online (Sandbox Code Playgroud)\n