Flutter - Prevent invalid data conversion default behavior

42 Views Asked by At

I would like to check whether a date entered by the user in DateTime format is valid or not, to convert it if it is valid and to display an exception if it is not

The problem is that Dart internally already converts that date for me into a valid date, example

The month of september has only 30 days and the test below returns false as dart converts the date 09/31/2023 to 10/01/2023 which is a valid date

expect(format.validDateTime(DateTime(2023, 9, 31)), false); // the test was supposed to return false, but it returns true

Is there a way to prevent this Dart conversion behavior and keep the date entered by the user?

1

There are 1 best solutions below

0
nvoigt On

If you want to parse it yourself, you can probably take the text before you convert it to DateTime.

Alternatively, use parseStrict with whatever format you find most useful:

import 'package:intl/intl.dart';

void main() {
  final moment = DateFormat('yyyy-MM-dd').parseStrict("2023-02-31");
  
  print(moment);
}

That will indeed throw an exception when you try:

Uncaught Error: FormatException: Error parsing 2023-02-31, invalid day value: 31 in en_US with time zone offset 1:00:00.000000.

What you cannot do however, is make a DateTime say "2023-02-31". Because it does not save it that way internally. It saves the milliseconds from a point in time in 1970, so whatever you pass it along, it will always be a valid date once transformed back from those milliseconds into days and months.