C# best way to compare two time of the day
26,426
Solution 1
How about:
internal static bool IsTimeOver()
{
return DateTime.Now.TimeOfDay > _whenTimeIsOver;
}
Operator overloading is very helpful for date and time work :) You might also want to consider making it a property instead of a method.
It's a slight pity that there isn't a
DateTime.CurrentTime
or
TimeSpan.CurrentTime
to avoid DateTime.Now.TimeOfDay
(just as there's DateTime.Today
) but alas, no...
I have a set of extension methods on int
in MiscUtil which would make the initialization of _whenTimeIsOver
neater - you'd use:
private static readonly TimeSpan _whenTimeIsOver = 16.Hours() + 25.Minutes();
It's not to everyone's tastes, but I like it...
Solution 2
if (DateTime.Now.TimeOfDay > _whenTimeIsOver)
....
Comments
-
Toto almost 2 years
I woulld like to know if a specified time of the day is passed. I don't really like the way I am doing:
private static readonly TimeSpan _whenTimeIsOver = new TimeSpan(16,25,00); internal static bool IsTimeOver() { return DateTime.Now.TimeOfDay.Subtract(_whenTimeIsOver ).Ticks > 0; }
How do you do?