我試過這樣
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
uj5u.com熱心網友回復:
YearMonth
您不能只創建LocalDate
一年中的一個月和一年,它只需要一個月中的一天(并且不提供任何默認值)。
由于您正在嘗試決議String
格式的 a "MM-uuuu"
,我假設您對創建 a 不感興趣LocalDate
,這不可避免地歸結為使用 a 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470820.html