Reputation: 33
I have a bool that tells me if the current time is in between two other times it will go dark at 8 (20:00) in the evening and light at 7 in the morning.. I am not sure if I should be doing 7 or 07 I have tried booth but still getting false?
Can anyone tell me why this is always returning false? Not much else to say really just that it's always returning false when it is currently in between the two times currently.. GTM Timezone London, Thanks!
public static bool NightTime
{
get
{
TimeSpan span = LastMoodlightUpdate - DateTime.Now;
TimeSpan start = new TimeSpan(20, 0, 0); //Dark at 20:00
TimeSpan end = new TimeSpan(07, 0, 0); //Light at 07:00
TimeSpan now = DateTime.Now.TimeOfDay;
return ((now > start) && (now < end));
}
}
Upvotes: 2
Views: 222
Reputation: 52250
I don't get the purpose of all your code. Isn't it as simple as this?
public static bool NightTime
{
get
{
var hour = System.DateTime.Now.Hour;
return (hour <=7 || hour >= 20);
}
}
Upvotes: 1
Reputation: 391336
The problem here is that comparing two TimeSpan
values is a simple numeric comparison.
As such, no time can both be larger than 20:00 and smaller than 07:00 in terms of values. We humans can deal with such incongruities, but the computer can't.
You need to consider what you want here:
|---------|..................................|-----------|
00 07 20 24
You want the times in dashes, basically you should use ||
instead of &&
:
return (now > start) || (now < end);
Since the time of day cannot be negative, nor can it reach 24:00 or higher, this will give you what you want.
Upvotes: 7