Home > Enterprise >  How format Date time using DateTimePicker and get the selected date as String?
How format Date time using DateTimePicker and get the selected date as String?

Time:07-06

I tried using this=> choosenFromCalender = DateFormat('dd-MM-yyyy').format(newValue);

but the for this error not able to format properly.

enter image description here

  DateTimePicker(
                           
                            dateMask: 'dd-MM-yyyy',
                            initialValue: DateTime.now().toString(),
                            type: DateTimePickerType.date,
                            firstDate: DateTime(1800),
                            lastDate: DateTime(2050),                                
                            onChanged: (newValue) {
                              print(newValue);  // for now its `2022-07-27` i want `27-07-2022`
                            
                            },

                            onSaved: (value) {

                            },
                          ),

CodePudding user response:

The Issue is that you get from the newValue a string back, but DateFormat can only handle DateTime formats. What you can do is, that you parse your String to a DateTime object.

DateTime dt = DateTime.parse(newValue);

The dt object you can use then to Format your DateTime.

But there is an better alternative. You can do both operations together.

 print(DateFormat('dd-MM-YYYY').parse(newValue));

Prints you the Formatted Date as you want with the value from the onChanged Method

CodePudding user response:

You need to formate picked date

for that you need to put below code in onChanged method

newValue=DateFormat('dd-MM-yyyy').format(DateTime.parse(newValue);
  • Related