By Alvin Alexander. Last updated: January 19, 2022
When using Flutter and Dart, if you need to compare two TimeOfDay
values, I can confirm that it helps to first convert the TimeOfDay
to a double
using this function:
/// note: 'hour' is in 24-hour format double _timeOfDayToDouble(TimeOfDay tod) => tod.hour + tod.minute/60.0;
Once you have several TimeOfDay
values converted to double
values:
var now = _timeOfDayToDouble(TimeOfDay.now()); var startTime = _timeOfDayToDouble(_startTime); // _startTime is a TimeOfDay var stopTime = _timeOfDayToDouble(_stopTime); // _stopTime is a TimeOfDay
you can then compare them like this:
if (now > startTime && now < stopTime) { // do your work here ... }
Related: Converting Flutter TimeOfDay to Dart DateTime
In a related note, if you have a Flutter TimeOfDay variable named tod
and want to convert it to a Dart DateTime variable, these approaches work:
// you already have some `TimeOfDay tod` // Option 1: if “today” doesn’t matter final dt = DateTime(1969, 1, 1, tod.hour, tod.minute); // Option 2: if “today” matters final now = DateTime.now(); final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
The DateTime
class has useful methods like isBefore
, isAfter
, difference
, etc., that you can use to compare two DateTime
variables, which may be easier, depending on your needs.
In summary, if you want to compare two Flutter TimeOfDay
variables, I hope these examples are helpful.