Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart/Flutter How to compare two TimeOfDay times?

Tags:

TimeOfDay documentation has no comparison operator and primitive comparison does not work. My only solution that I can thinking of right now is to convert TimeOfDay to DateTime and use DateTime's difference method.

Does anyone have a better solution?

like image 947
Jesse Avatar asked Feb 11 '19 22:02

Jesse


People also ask

How do you compare two DateTime darts?

Simply use the methods isAfter() , isBefore() or isAtSameMomentAs() from DateTime . Other alternative, use compareTo(DateTime other) , as in the docs: Compares this DateTime object to [other], returning zero if the values are equal. Returns a negative value if this DateTime [isBefore] [other].

How do you convert TimeOfDay to time in flutter?

Related: Converting Flutter TimeOfDay to Dart DateTime // 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.


2 Answers

Convert it to a double then compare.

double toDouble(TimeOfDay myTime) => myTime.hour + myTime.minute/60.0

like image 180
Lucas Avatar answered Sep 19 '22 09:09

Lucas


Thanks from @Lucas idea, you can calculate hour and minute by

TimeOfDay yourTime ; 
TimOfDay nowTime = TimeOfDay.now()

double _doubleYourTime = yourTime.hour.toDouble() +
            (yourTime.minute.toDouble() / 60);
double _doubleNowTime = nowTime.hour.toDouble() +
            (nowTime.minute.toDouble() / 60);

double _timeDiff = _doubleYourTime - _doubleNowTime;

double _hr = _timeDiff.truncate();
double _minute = (_timeDiff - _timeDiff.truncate()) * 60;

print('Here your Happy $_hr Hour and also $_minute min');