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:
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?
CodePudding user response:
Your date format is not regular(yyyy-MM-dd) format, you need to use custom format to format it, so instead of this:
DateTime eDate = DateTime.parse(_eDate.text);
DateTime sDate = DateTime.parse(_sDate.text);
eDate = DateFormat("yyyy-MM-dd").format(eDate);
You can use intl package and do this::
DateTime eDate = DateFormat("dd/MM/yyyy").parse(_eDate.text);
also in line four of your code, format(eDate)
return you a string
, you can't pass it to eDate
, because it is DateTime
. Also you don't need this line at all.
CodePudding user response:
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:
DateTime now = DateTime.now();
String formattedDate = DateFormat.yMMMEd().format(now);
print(formattedDate);
Output:
Tue, Jan 25, 2022
2.- Using Custom Pattern
DateTime now = DateTime.now();
formattedDate = DateFormat('EEEE, MMM d, yyyy').format(now);
print(formattedDate);
Output:
Tuesday, Jan 25, 2022
For more information: https://api.flutter.dev/flutter/intl/DateFormat-class.html
I hope it was useful for you.