When working on a Flutter/Dart project where I had to parse different methods entering dates into a form, I found that if the user wrote i.e (by accident) '09.13' for december 9th (wrote 13 instead of 12), the parse result for parse rolled over to january next year.
Given in code:
DateTimeFormat format = 'dd.MM';
try{
var dateTime = format.parse('09.13');
print("dateTime = ${dateTime.toString()}");
}on FormatException{
print("dateTime error");
}
I expected this to be
dateTime error
but instead I got
dateTime = 1971-01-09 00:00:00.000
I understand the reset to 1970, since I didn't give any year, I'd rather expect it to give a FormatException
to show the user that there is a flaw in the entered date... ...but rolling over to the next year (1971) and give no Exception ?
Is there any reason for this behavior, or do I simply need to fight with RegEx for this dateTime check...
CodePudding user response:
this is actually, not something to fix, the DateFormat
algorithm was made to calculate the expected DateTime from the input:
9 days and 13 months logically equal 1 year, 1 month, and 9 days.
However, using dart
you can throw your own custom FormatException
, as example you could do something like this:
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;
}
Now if the month is above 12, the method will return false, so it enter the else block, then throws the FormatException
, which will be catched in the catch block.