How to remove time in datepicker

Viewed 65

enter image description here

 MaterialButton(
   onPressed: _showDatePicker,
   color: Colors.blue,
   child: const Text(
      'choose date',
      style: TextStyle(color: Colors.white, fontSize: 25),
   ),
 ),
  //date picker
  DateTime _dateTime = DateTime(2020);

  void _showDatePicker() {
    showDatePicker(
      context: context,
      initialDate: DateTime(2020, 1, 1),
      firstDate: DateTime(2020),
      lastDate: DateTime(2023),
    ).then((value) {
      setState(() {
        _dateTime = value!;
      });
    });
  }

4 Answers

use intl package and do this:

void _showDatePicker() {
    showDatePicker(
      context: context,
      initialDate: DateTime(2020, 1, 1),
      firstDate: DateTime(2020),
      lastDate: DateTime(2023),
    ).then((value) {
      if (value != null) {
        var result = DateFormat('yyyy-MM-dd').format(value);
        setState(() {
          _dateTime = result;
        });
      }
    });
  }

You can do something like this:

DateTime(date.year, date.month, date.day)

or just use

DateUtils.dateOnly(date)

showDatePicker provide nullable DateTime on return.

Future<DateTime?> showDatePicker({

That's why when we are assigning value on _dateTime you need to use ! Unless we null check 1st. ! means we say this value is not null.

Directly using ! will crash the app when user press cancel button on date picker. If you like to check the error, remove if condition and use ! directly.

  DateTime _dateTime = DateTime(2020);
  void _showDatePicker() {
    showDatePicker(
      context: context,
      initialDate: DateTime(2020, 1, 1),
      firstDate: DateTime(2020),
      lastDate: DateTime(2023),
    ).then((value) {
      if (value != null) { 
        setState(() {
          _dateTime = value;
        });
      }
    });
  }

To remove time from text you can use

  Text("${_dateTime.year} ${_dateTime.month} ${_dateTime.day} "),

Also using intel package provide more option.

Related