Flutter check if DateTime actually exists
In my app the user can add a DateTime
. For that I am not using a simple DatePicker
but instead something custom, where I get two Strings
for each Day & Month (dd, mm). My problem right now is that I need to validate this input. And I tried a couple of things but couldn't get a good working solution!
DateTime getDateTime(BuildContext context) {
return DateTime(2021, (m1! * 10 + m2!), (d1! * 10 + d2!));
}
This is what Ive tried. The problem is that the user can also give me anything (any int
) for m1, m2, d1 and d2 and DateTime
simply formats that in a regular DateTime.
Is there a way to check if a given DateTime in the past existed?
German format
01.05. -> true
00.05. -> false
51.05. -> false
31.02. -> false
15.10. > true
I implemented by using 'parseStrict' method in DateFormat.
The 'parseStrict' throw exception does not match real date.
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;
}
}
Usage
isValidDate(m1: 1, m2: 1, d1: 3, d2: 0);