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