Flutter 检查 DateTime 是否确实存在
Flutter check if DateTime actually exists
在我的应用程序中,用户可以添加 DateTime
。为此,我没有使用简单的 DatePicker
,而是使用一些自定义的东西,我在每个日和月 (dd, mm) 得到两个 Strings
。我现在的问题是我需要验证这个输入。我尝试了一些方法,但无法找到有效的解决方案!
DateTime getDateTime(BuildContext context) {
return DateTime(2021, (m1! * 10 + m2!), (d1! * 10 + d2!));
}
这是我试过的。问题是用户还可以为 m1、m2、d1 和 d2 提供任何内容(任何 int
),而 DateTime
只是将其格式化为常规 DateTime。
有没有办法检查过去给定的日期时间是否存在?
德语格式
01.05. -> true
00.05. -> false
51.05. -> false
31.02. -> false
15.10. > true
我是在 DateFormat 中使用 'parseStrict' 方法实现的。
'parseStrict'抛出的异常与实际日期不匹配。
bool isValidDate({y = 2021, m1, m2, d1, d2}) {
DateFormat format = DateFormat('yyyy/M/d');
try {
String md = '$y/${m1 * 10 + m2}/${d1 * 10 + d2}';
format.parseStrict(md);
return true;
} catch (error) {
return false;
}
}
用法
isValidDate(m1: 1, m2: 1, d1: 3, d2: 0);
我们可以用其他方式检查...
static bool isDate(String dt) {
try {
final date = DateTime.parse(dt);
final y = date.year.toString().padLeft(4, '0');
final m = date.month.toString().padLeft(2, '0');
final d = date.day.toString().padLeft(2, '0');
final newDt = "$y-$m-$d";
return dt == newDt;
} catch (e) {
return false;
}
}
if(isDate('2021-02-04){
//Yes Correct
} else {
//Not Correct
}
在我的应用程序中,用户可以添加 DateTime
。为此,我没有使用简单的 DatePicker
,而是使用一些自定义的东西,我在每个日和月 (dd, mm) 得到两个 Strings
。我现在的问题是我需要验证这个输入。我尝试了一些方法,但无法找到有效的解决方案!
DateTime getDateTime(BuildContext context) {
return DateTime(2021, (m1! * 10 + m2!), (d1! * 10 + d2!));
}
这是我试过的。问题是用户还可以为 m1、m2、d1 和 d2 提供任何内容(任何 int
),而 DateTime
只是将其格式化为常规 DateTime。
有没有办法检查过去给定的日期时间是否存在?
德语格式
01.05. -> true
00.05. -> false
51.05. -> false
31.02. -> false
15.10. > true
我是在 DateFormat 中使用 'parseStrict' 方法实现的。
'parseStrict'抛出的异常与实际日期不匹配。
bool isValidDate({y = 2021, m1, m2, d1, d2}) {
DateFormat format = DateFormat('yyyy/M/d');
try {
String md = '$y/${m1 * 10 + m2}/${d1 * 10 + d2}';
format.parseStrict(md);
return true;
} catch (error) {
return false;
}
}
用法
isValidDate(m1: 1, m2: 1, d1: 3, d2: 0);
我们可以用其他方式检查...
static bool isDate(String dt) {
try {
final date = DateTime.parse(dt);
final y = date.year.toString().padLeft(4, '0');
final m = date.month.toString().padLeft(2, '0');
final d = date.day.toString().padLeft(2, '0');
final newDt = "$y-$m-$d";
return dt == newDt;
} catch (e) {
return false;
}
}
if(isDate('2021-02-04){
//Yes Correct
} else {
//Not Correct
}