H. Allaoui
H. Allaoui

Reputation: 361

Flutter : How to Convert DateTime to TimeOfDay?

I have this code of time picker, then I want to set the initial Time from a DateTime variable:

Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay pickedS = await showTimePicker(
    context: context,
    initialTime: createdAt,
    builder: (BuildContext context, Widget child) {
       return MediaQuery(
         data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
        child: child,
      );});

if (pickedS != null && pickedS != selectedTime )
  setState(() {
    selectedTime = pickedS;
    myTweets[actualTweetIndex].createdAt = dateFormat.format(selectedDate.toLocal()) +' ${selectedTime.hour}:${selectedTime.minute}:00 +0000 '+ selectedDate.year.toString();
  });

}

Upvotes: 15

Views: 7728

Answers (1)

F Perroch
F Perroch

Reputation: 2225

The TimeOfDay class has a dedicated constructor for that:

TimeOfDay.fromDateTime(DateTime time)

You can check the documentation here

Upvotes: 39

Related Questions