views:

852

answers:

2

Hello,

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 ?

+8  A: 
if (DateTime.Now.TimeOfDay > _whenTimeIsOver)
    ....
Philippe Leybaert
+1 for being first.
Vadim
+1 for somehow being faster than Jon
Steven Sudit
I was faster, but my initial answer contained a small error :)
Philippe Leybaert
+11  A: 

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...

Jon Skeet
Ok thought we cannot compare DateTime and TimeSpan object, I was wrong. I like the initilaisation.
Toto
@Duaner: You're not comparing `DateTime` with `TimeSpan` - you're comparing two `TimeSpans`. The `TimeOfDay` property returns `TimeSpan`.
Jon Skeet