我是这样试的

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

Java相关问答推荐

编译期间错误(Java 0000)Android .Net MAUI

我可以从Java模块中排除maven资源文件夹吗?

使用包私有构造函数强制子类Java类

Helidon 4和Http API

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

把一条整型短裤和两条短裤装成一条长的

基于接口的投影、原生查询和枚举

如何在我的世界中为互动增加冷却时间?

无法将GSON导入到我的JavaFX Maven项目

对从Spring Boot 3.1.5升级到3.2.0的方法的查询验证失败

如何在字节数组中反转UTF-8编码?

如何通过Java java.lang.Foreign API访问本机字节数组

将java.util.Date(01.01.0001)转换为java.time.LocalDate将返回29.12.0000

Maven-Dependency-Plugin 3.6.+开始查找在依赖关系:分析目标期间找到的新的使用的未声明依赖关系

JPA无手术同品种器械可能吗?

为什么Spring要更改Java版本配置以及如何正确设置?

java.lang.NoSuchMethodError:';org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream$Builder org.apache.poi-poi-ooxml-5.2.4

ReturnedRect在升级后反转

java构造函数中的冻结操作何时发生?

如何使用Jackson读取以方括号开头的JSON?