svw
svw

Reputation: 9

How to check if the current time falls in a particular range of time?

I want to create a trigger. I give two inputs. a)Start Time b)End time.

I want to continuously check if the current time falls between start time and end time. And toggle the value of a global variable between 0(not in range) and 1(in range).

But I need to check it every sec.

what I am doing now is following

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

But I get nothing and the program hangs.

Is there any other way to check whether the current time falls in the range

or

change the value of the alert_trigger to 1 between start and end time and 0 otherwise..

Upvotes: 0

Views: 1137

Answers (4)

Luc Morin
Luc Morin

Reputation: 5380

I assume start and end are of type DateTime:

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

Cheers

Upvotes: 1

Gustav
Gustav

Reputation: 55816

I would use the CompareTo method:

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;

If start and end time should be excluded, you can reduce to:

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

Upvotes: 0

Masoud AMR
Masoud AMR

Reputation: 134

use from DateTime.compare

private void compareTime(DateTime start, DateTime end)
{
    DateTime cur = DateTime.Now;
    if(DateTime.compare(cur, start)>0 && DateTime.compare(cur, end)<0)
        return 1;
    else
        return 0;
}

Upvotes: 0

nozzleman
nozzleman

Reputation: 9649

Work with TimeSpan instead of 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
    }
}   

Also, think about another solution but active waiting in a while loop. Maybe subscribing to a Tick-event of a Timer.

Upvotes: 0

Related Questions