skip to Main Content

I want to change the default flutter (dart) date picker date format. The default format of date picker is
"YYYY/MM/DD". But I want to change to "DD-MM-YYYY".
That is, e.g. from 2024/05/21 to 21-05-2024

Below is my function code base, but this isn’t working for me.
Please how do I convert it correctly.

 onTap: () async {
                  await showDatePicker(
                          context: context,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(1960),
                          lastDate: DateTime(2040)
                          )
                      .then((value) {
                    setState(() {
                      dob = value.toString();
                    });
                    
                  });
                },

I have tried,

 onTap: () async {
                  await showDatePicker(
                          context: context,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(1960),
                          lastDate: DateTime(2040)
                          )
                      .then((value) {
                    setState(() {
                      dob = value.toString();
                    });
                    
                  });
                },

And I got,
2024/05/21 instead.

I want to get 21-05-2024

2

Answers


  1. Chosen as BEST ANSWER

    This code worked for me.

     onTap: () async {
              await showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(1960),
                      lastDate: DateTime(2040)
                      )
                  .then((value) {
                setState(() {
                  DateFormat formatter = DateFormat('dd-MM-yyyy');
                  dob = formatter.format(value!);
                });
                
              });
            },
    

  2. To achieve your desired output you can use a package called intl.

    First add intl 0.19.0 to your dependencies.

       import 'package:intl/intl.dart';
    
       // ...
    
       onTap: () async {
                  await showDatePicker(
                          context: context,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(1960),
                          lastDate: DateTime(2040)
                          )
                      .then((value) {
                    setState(() {
                      DateFormat formatter = DateFormat('dd-MM-yyyy');
                      dob = formatter.format(value);
                    });
                    
                  });
                },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search