By Alvin Alexander. Last updated: September 19, 2019
If you ever need a Dart/Flutter method to format a TimeOfDay variable — i.e., convert a TimeOfDay
to a String
— I can confirm that this method works:
String formatTimeOfDay(TimeOfDay tod) {
final now = new DateTime.now();
final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
final format = DateFormat.jm(); //"6:00 AM"
return format.format(dt);
}
As shown, this code convert a Flutter TimeOfDay
to a Dart DateTime
, which you can then format with DateFormat. That DateFormat
class link shows a lot of other ways you can convert a DateTime
to a String
, such as this:
var fmt = DateFormat("HH:mm").format(now);
In summary, if you need to convert a Flutter TimeOfDay
to a String
, I hope this example function is helpful.