Flutter, couldn't convert string to Date time format

1.5k Views Asked by At

I got data input in TextField using showDatePicker. I converted the selected data to String and parsed it to the format dd-mm-yy using intl format. According to docs DateFormat('ymd') is the way to do that. But I get the error FormatException: Trying to read m from 2022-06-04 00:00:00.000 at position 4. What is right way to convert to that format and why am I getting that error. docs that I referred - https://api.flutter.dev/flutter/intl/DateFormat-class.html

code

TextField(
                  keyboardType: TextInputType.datetime,
                  controller: paidDateController,
                  onTap: () async {
                    DateTime? PickedDate = await showDatePicker(
                        context: context,
                        initialDate: DateTime.now(),
                        firstDate: DateTime(2010),
                        lastDate: DateTime(2026));

                    if (PickedDate != null) {
                      setState(() {
                        formatDate = PickedDate.toString();
                        paidDate = DateFormat('ymd').parse(formatDate);
                        print(paidDate);
                      });
                    } else {
                      Get.snackbar('Error', 'Pick paid date',
                          backgroundColor: Colors.red);
                    }
                  },
                  decoration:
                      kTextFieldDecocation.copyWith(hintText: 'Paid Date'),
                ), 

formatDate is string data type and paidDate is date time data type.

1

There are 1 best solutions below

2
On

hmmmm ithink the formating you giving to this part

paidDate = DateFormat('ymd').parse(formatDate);

show always error since if you tried to parse the date was format given by showDateTimePicker would be like 2022-06-05 15:00:12 which also if you try to pass this. This would like likely not to parse since DateFormat('yMd') or DateFormat.yMd() which the reading pattern date of this is like this "05/06/2022" so you try to is like this

final formatDate1 = "2022-05-06";
   final formForMatted = DateFormat('dd/MM/yyyy').format(DateTime.parse(formatDate1));
   final  paidDate1 = DateFormat.yMd().parse(formForMatted);
   print(paidDate1); // as result 2022-06-05 00:00:00.000

but if you wanted a result like 5/6/2022 try this

final formatDate1 = "2022-05-06";
   final paidDate1 = DateFormat.yMd().format(DateTime.parse(formatDate1));
   print(paidDate1); // as result 5/6/2022