简体   繁体   中英

C# time bool always returning false

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));
    }
}

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM