TL;博士
MonthDay.parse(
"12.31" ,
DateTimeFormatter.ofPattern("MM.dd")
)
捕捉DateTimeParseException
爲無效的輸入。
java.time.MonthDay
現代的方法使用java.time類,而不是在問題中看到的麻煩遺產類。
其中java.time類是MonthDay
,正是你所需要的。
我建議收集輸入爲兩個不同的數字。
MonthDay md = MonthDay.of(x , y) ;
如果你堅持,你可以收集輸入爲一個組合字符串和parse。如果是這樣,我建議你和你的用戶使用標準ISO 8601格式:--MM-DD
。
MonthDay md = MonthDay.parse("--12-31") ;
或者使用DateTimeFormatter
定義模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern("MM.dd") ;
MonthDay md = MonthDay.parse(input , f) ;
陷阱爲DateTimeParseException
檢測無效輸入。
String input = "13.10" ; // Invalid input. Month must be 1-12.
DateTimeFormatter f = DateTimeFormatter.ofPattern("MM.dd") ;
MonthDay md = null ;
try
{
md = MonthDay.parse(input , f) ;
} catch (DateTimeParseException e) {
// … handle error …
System.out.println("Invalid input: " + input) ;
}
看到這個code run live at IdeOne.com。
輸入無效:13.10
E:java.time.format.DateTimeParseException:文本'13 0.10' 無法解析:無法從TemporalAccessor獲得MONTHDAY:{MonthOfYear = 13,DAYOFMONTH = 10},型的ISO java.time.format.Parsed
md.toString():空
A *魔術師* ...?它看起來像字段只是將最接近的近似值返回到它可以有效的日期。更清楚地描述問題所在。 – hnefatl
請發表[mcve]。然後描述您所執行的**精確**步驟和程序顯示的**精確**行爲。如有必要,請使用屏幕截圖補充您的描述。 –
僅供參考,您正在使用現在已遺留的麻煩的舊類,由java.time類取代。 –