如何检查当前时间是否落在特定时间范围内?

时间:2015-06-28 05:40:54

标签: c# time range

我想创建一个触发器。 我给出了两个输入。 a)开始时间 b)结束时间。

我想不断检查当前时间是否介于开始时间和结束时间之间。并将全局变量的值在0(不在范围内)和1(在范围内)之间切换。

但我需要每隔一秒检查一次。

我现在正在做的是

while (true)
{
    now_hrs = Convert.ToInt32(DateTime.Now.Hour);
    now_min = Convert.ToInt32(DateTime.Now.Minute);

    if (now_hrs >= start_hrs && now_hrs <= end_hrs)
    {
        if (now_hrs == start_hrs && now_min < start_min)
        {

        }
        else if (now_hrs == end_hrs && now_min > end_min)
        {

        }
        else
        {
            alert_trigger = 1;
        }
    }
}

但是我什么也没得到,程序就挂了。

还有其他方法可以检查当前时间是否在

范围内

在开始和结束时间之间将alert_trigger的值更改为1,否则为0 ..

4 个答案:

答案 0 :(得分:1)

我认为int itemID = int.parse(e.commandArgument) switch(e.commandName) { case 'DoEdite' :{//some Code Viewstate["ID"] = itemID; break;} case 'DoDelete' :{//some Code break;} } start的类型为end

DateTime

干杯

答案 1 :(得分:0)

使用window.onload = function() { //Creates variable count var count = 0; //Runs through json file in a loop so the count can find the object amount $.getJSON("/quake/quake.txt", function(json1) { $.each(json1, function(key, data) { count = count + 1; count = count - (Number(data.mag) < 3.1); console.log(count); }); //Displays count in element with ID quakecount document.getElementById("quakecount").innerHTML += "Magnitude 3.1+ Earthquakes Displayed: " + count; }); } 代替TimeSpan

DateTime

另外,考虑另一个解决方案,但在var start = new TimeSpan(7, 0, 0); // your start time var end = new TimeSpan(15, 0, 0); // your end time while(true) { var now = DateTime.Now.TimeOfDay; if (now <= end && now >= start) { alert_trigger = 1 } } 循环中进行主动等待。也许订阅while - Tick的事件。

答案 2 :(得分:0)

使用while(true) { DateTime now = DateTime.Now; alert_trigger = (now > start && now < end) ? 1 : 0; }

DateTime.compare

答案 3 :(得分:0)

我会使用CompareTo方法:

DateTime start = DateTime.Today.AddHours(10).AddMinutes(15);
DateTime end = DateTime.Today.AddHours(10).AddMinutes(30);
DateTime now = DateTime.Now;

while(true)
{
    alert_trigger = (now.CompareTo(start) >= 0 && now.CompareTo(end) <= 0) ? 1 : 0;

如果应排除开始和结束时间,您可以减少到:

while(true)
{
    alert_trigger = (now.CompareTo(start) + now.CompareTo(end) = 0) ? 1 : 0;
}  
相关问题