I have a form, the date picker is supposed to validate and check whether the end date is later than the start date. But my coding got error which says
Invalid date format
09/01/2023`
Here is my validation code:
TextEditingController _sDate = TextEditingController();
TextEditingController _eDate = TextEditingController();
String? endDateValidator(value) {
DateTime eDate = DateTime.parse(_eDate.text);
DateTime sDate = DateTime.parse(_sDate.text);
eDate = DateFormat("yyyy-MM-dd").format(eDate);
if (_sDate != null && _eDate == null) {
return "select Both data";
}
if (_eDate == null) return "select end date";
if (_eDate != null) {
if(eDate.isBefore(sDate))
return "End date must be after start date";
}
return null;}
How do I fix this?
2
Answers
Your date format is not regular(yyyy-MM-dd) format, you need to use custom format to format it, so instead of this:
You can use intl package and do this::
also in line four of your code,
format(eDate)
return you astring
, you can’t pass it toeDate
, because it isDateTime
. Also you don’t need this line at all.There are two methods of formatting dates if we are working in Flutter:
1.- Add the intl package (https://pub.dev/packages/intl) and you can access to this functions:
2.- Using Custom Pattern
For more information:
https://api.flutter.dev/flutter/intl/DateFormat-class.html
I hope it was useful for you.