Alex Rivera | Logout

How can I check if the current time is between in a time frame?

Asked 2009-02-26T20:17:42.263
21

I have a service that user can configure to run during "off-peak" hours. They have the ability to set the time frame that the service can run.

For Example:

User A works 8am-5pm, so they want to schedule the app to run between 5:30pm and 7:30am.

User B works 9pm-6am, so they schedule the app to run between 6:30am and 8:30 pm.

The point is that the app uses their computer while they are not.

Given a DateTime of the current time, a DateTime of the start and a DateTime of the stop time, how can I check if current is between start and stop.

The tricky part for me is that the time can cross the midnight boundary.

Edit
Report

2 Answers

47

If startTime and endTime represent a single time interval (it will only happen once, and startTime and endTime represent the date and the time to start/stop), then it's as easy as saying

bool isTimeBetween = someTime >= startTime && someTime <= endTime;

If it's a recurring event (happens every day, during some interval), you can do comparisons using the TimeOfDay property. (The recurring case is the one where you have to consider a start/stop that crosses midnight)

static public bool IsTimeOfDayBetween(DateTime time, 
                                      TimeSpan startTime, TimeSpan endTime)
{
    if (endTime == startTime)
    {
        return true;   
    }
    else if (endTime < startTime)
    {
        return time.TimeOfDay <= endTime ||
            time.TimeOfDay >= startTime;
    }
    else
    {
        return time.TimeOfDay >= startTime &&
            time.TimeOfDay <= endTime;
    }

}

(Note: This code assumes that if start == end, then it covers all times. You made a comment to this effect on another post)

For example, to check if it's between 5 AM and 9:30 PM

IsTimeOfDayBetween(someTime, new TimeSpan(5, 0, 0), new TimeSpan(21, 30, 0))

If startTime and endTime are DateTimes, you could say

IsTimeOfDayBetween(someTime, startTime.TimeOfDay, endTime.TimeOfDay)
answered 2009-02-26T20:19:41.463
2

So I assume from the question that you want to know if given a start time and end time for a day (not including the actual date, i.e., 1/1/1900 or something like that) to see if another time is with the time specified by start and end. E.g., if start is 9pm and end is 9am, accept 10pm but reject 10am.

You can do this either per time range types (times are equal, end is after start, end is before start) which is simple:

if (end==start) return true
else if (end>start) return start<=time && time<=end
else return !(time>end && time<start)

Or you can extend the range of start and end such that end is always after start as such:

if (end<=start) end += <24 hours>
if (time<start) time+= <24 hours>
return time<=end
answered 2009-02-26T21:00:44.423

Your Answer