C# best way to compare two time of the day
Asked Answered
B

2

11

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?

Banquette answered 11/9, 2009 at 14:13 Comment(0)
P
24

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

Pashalik answered 11/9, 2009 at 14:15 Comment(2)
Ok thought we cannot compare DateTime and TimeSpan object, I was wrong. I like the initilaisation.Banquette
@Duaner: You're not comparing DateTime with TimeSpan - you're comparing two TimeSpans. The TimeOfDay property returns TimeSpan.Pashalik
H
14
if (DateTime.Now.TimeOfDay > _whenTimeIsOver)
    ....
Hylozoism answered 11/9, 2009 at 14:15 Comment(1)
I was faster, but my initial answer contained a small error :)Hylozoism

© 2022 - 2024 — McMap. All rights reserved.