Home > database >  Showing date in HH:mm using TimePicker in Flutter
Showing date in HH:mm using TimePicker in Flutter

Time:10-06

I'm trying to display the selected time from TimePicker in HH:mm format but end up hitting this error. I would therefore like to know where I'm going wrong. The error I get is:

Unhandled Exception: FormatException: Trying to read HH from TimeOfDay(00:30) at position 0

Here is my code:

TimeOfDay _toTime = TimeOfDay.now();
String closingTime = '';

    InkWell(
                                  onTap: () => showTimePicker(
                                          context: context,
                                          initialTime: _toTime,
                                          builder: (context, child) => MediaQuery(
                                              data: MediaQuery.of(context).copyWith(
                                                  alwaysUse24HourFormat: true),
                                              child: child ?? Container()))
                                      .then((value) {
                                    setState(() {
                                      _toTime = value!;
                                      // closingTime = _toTime.format(context);
                                      closingTime = DateFormat('HH:mm')
                                          .parse(_toTime.toString())
                                          .toString();
                                      print('CLOSING TIME: $closingTime');
                                    });
                                  })
    )

CodePudding user response:

Hope the following cod with help you.

var dt = DateFormat("h:mm a").parse(_toTime.format(context));
closingTime = DateFormat('HH:mm').format(dt);

CodePudding user response:

First try to convert your time to DateTime then format it with Hm ,like this:

setState(() {
   if (time != null) {
     _toTime = time;
     final now = new DateTime.now();
     var newDatetime = DateTime(now.year, now.month, now.day, _toTime.hour, _toTime.minute);
     closingTime = DateFormat.Hm().format(newDatetime).toString();

     print('CLOSING TIME: $closingTime'); // ex: CLOSING TIME: 04:46
   }
});
  • Related