简体   繁体   English

C#time bool总是返回false

[英]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? 我有一个布尔告诉我,如果当前时间介于两个其他时间之间,它将在晚上8点(20点)变暗,早上7点点亮。我不确定我是否应该做7或07我试过摊位但仍然变得虚假?

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! 没有什么可说的,只是当它目前处于两次之间时总是返回假.. GTM Timezone London,谢谢!

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. 这里的问题是比较两个TimeSpan值是一个简单的数字比较。

As such, no time can both be larger than 20:00 and smaller than 07:00 in terms of values. 因此,就值而言,没有时间可以大于20:00且小于07:00。 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. 由于时间不能为负,也不能达到24:00或更高,这将给你你想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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