在處理 Flutter/Dart 專案時,我必須決議將日期輸入表單的不同方法,我發現如果用戶在 12 月 9 日寫了 ie(意外)'09.13'(寫了 13 而不是 12),決議結果for parse 延期到明年 1 月。
在代碼中給出:
DateFormat format = 'dd.MM';
try{
var dateTime = format.parse('09.13');
print("dateTime = ${dateTime.toString()}");
}on FormatException{
print("dateTime error");
}
我希望這是
dateTime error
但相反我得到了
dateTime = 1971-01-09 00:00:00.000
我理解重置為 1970 年,因為我沒有給出任何年份,我寧愿期望它能夠向FormatException用戶顯示輸入的日期存在缺陷......但滾動到下一個年(1971 年)并且沒有例外?
這種行為有什么原因嗎,還是我只需要與 RegEx 對抗這個 dateTime 檢查......
uj5u.com熱心網友回復:
實際上,這不是要解決的問題,該DateFormat演算法用于根據輸入計算預期的 DateTime:
9天13個月邏輯上等于1年1個月9天。
但是,使用dart您可以拋出自己的 custom FormatException,例如,您可以執行以下操作:
try{
String stringDate = "09.13";
if(checkMonthLimit(stringDate)) {
var dateTime = format.parse(stringDate);
print("dateTime = ${dateTime.toString()}");
} else {
throw FormatException("some text here");
}
}on FormatException{
print("dateTime error");
}
bool checkMonthLimit(String txt) {
return int.parse(txt.split(".")[1]) <= 12;
}
現在如果月份大于 12,該方法將回傳 false,因此它進入 else 塊,然后拋出FormatException,它將在 catch 塊中捕獲。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532398.html
