0

How can I format the date and change from:

current output

to just dd/mm/yyyy?

input field code:

    textFields.add(
    GestureDetector(
      onTap: () => _selectDate(context),
      child: AbsorbPointer(
        child: TextFormField(
          style: TextStyle(
             fontSize: 12.0
          ),
          controller: _date,
          keyboardType: TextInputType.datetime,
          decoration: InputDecoration(
            isDense: true,
            fillColor: Colors.white,
            hintText: 'Date of Birth',
            filled: true,
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(width: 0.0),
            ),
            contentPadding: const EdgeInsets.only(left: 14.0, bottom: 10.0, top: 10.0),
          ),
          onSaved: (value) => _dateOfBirth  = value,
        ),
      ),
    ));

_selectDate method:

  DateTime selectedDate = DateTime.now();
  TextEditingController _date = new TextEditingController();

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(1901, 1),
        lastDate: DateTime(2100));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
        _date.value = TextEditingValue(text: picked.toString());
      });
  }
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
TJMitch95
  • 421
  • 3
  • 7
  • 23
  • 1
    Follow this answer: https://stackoverflow.com/questions/51579546/how-to-format-datetime-in-flutter – Alok Aug 10 '20 at 18:41

2 Answers2

1

You can use the DateFormat class of the intl package. You'll have to add intl: ^0.16.1 as a dependency in your pubspec.yaml. Latest version can be found here.

You can specify the exact format you want your date to be outputted as.

Ex.

import 'package:intl/intl.dart';//Import intl in the file this is being done

Future<Null> _selectDate(BuildContext context) async {
    DateFormat formatter = DateFormat('dd/MM/yyyy');//specifies day/month/year format

    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(1901, 1),
        lastDate: DateTime(2100));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
        _date.value = TextEditingValue(text: formatter.format(picked));//Use formatter to format selected date and assign to text field
      });
  }
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
0
    DateTime now = DateTime.now();   //current date
    DateFormat formatter = DateFormat('yyyy-MM-dd'); // use any format
    String formatted = formatter.format(now);
    print(formatted); // something like 2013-04-20

if you have date picker than

        DateFormat formatter = DateFormat('yyyy-MM-dd'); // use any formate
    String formatted = formatter.format(picked);
Johny Saini
  • 879
  • 1
  • 5
  • 6