skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search