如果将不存在/不真实的日期(例如:“ 20181364”(2018/13/64))传递到DateTime(构造函数或解析方法)中,则不会引发任何异常。而是返回计算出的DateTime。
示例: '20181364'-> 2019-03-05 00:00:00.000
如何检查给定日期是否确实存在/有效?
我试图使用DartPad解决此问题(但没有成功),因此这里不需要Flutter doctor输出。
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) => print(convertToDate(input)));
}
String convertToDate(String input){
return DateTime.parse(input).toString();
}
如果有某种方法可以检查给定日期是否确实存在/有效,那就太好了,例如:
您将如何解决?
答案 0 :(得分:3)
您可以将解析的日期转换为原始格式的字符串,然后比较是否与输入匹配。
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) {
print("$input is valid string: ${isValidDate(input)}");
});
}
bool isValidDate(String input) {
final date = DateTime.parse(input);
final originalFormatString = toOriginalFormatString(date);
return input == originalFormatString;
}
String toOriginalFormatString(DateTime dateTime) {
final y = dateTime.year.toString().padLeft(4, '0');
final m = dateTime.month.toString().padLeft(2, '0');
final d = dateTime.day.toString().padLeft(2, '0');
return "$y$m$d";
}
答案 1 :(得分:3)
我用来验证生日的解决方案是这样,我们可以看到它具有the年的计算。
class DateHelper{
/*
* Is valid date and format
*
* Format: dd/MM/yyyy
* valid:
* 01/12/1996
* invalid:
* 01/13/1996
*
* Format: MM/dd/yyyy
* valid:
* 12/01/1996
* invalid
* 13/01/1996
* */
static bool isValidDateBirth(String date, String format) {
try {
int day, month, year;
//Get separator data 10/10/2020, 2020-10-10, 10.10.2020
String separator = RegExp("([-/.])").firstMatch(date).group(0)[0];
//Split by separator [mm, dd, yyyy]
var frSplit = format.split(separator);
//Split by separtor [10, 10, 2020]
var dtSplit = date.split(separator);
for (int i = 0; i < frSplit.length; i++) {
var frm = frSplit[i].toLowerCase();
var vl = dtSplit[i];
if (frm == "dd")
day = int.parse(vl);
else if (frm == "mm")
month = int.parse(vl);
else if (frm == "yyyy")
year = int.parse(vl);
}
//First date check
//The dart does not throw an exception for invalid date.
var now = DateTime.now();
if(month > 12 || month < 1 || day < 1 || day > daysInMonth(month, year) || year < 1810 || (year > now.year && day > now.day && month > now.month))
throw Exception("Date birth invalid.");
return true;
} catch (e) {
return false;
}
}
static int daysInMonth(int month, int year) {
int days = 28 + (month + (month/8).floor()) % 2 + 2 % month + 2 * (1/month).floor();
return (isLeapYear(year) && month == 2)? 29 : days;
}
static bool isLeapYear(int year)
=> (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 );
}
答案 2 :(得分:1)
在 2020 年 12 月为 dart 添加了对验证日期的支持:https://pub.dev/documentation/intl/latest/intl/DateFormat/parseStrict.html