Home > Enterprise >  How to remove time in datepicker
How to remove time in datepicker

Time:08-26

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!;
      });
    });
  }

CodePudding user response:

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;
        });
      }
    });
  }

CodePudding user response:

You can do something like this:

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

or just use

DateUtils.dateOnly(date)

CodePudding user response:

You'll probably need to use this to format this date the way you want it https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

CodePudding user response:

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