Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 710
scottm Avatar asked Feb 26 '09 20:02

scottm


People also ask

How do you find the time between two times in python?

Use datetime. strptime() to Calculate Time Difference Between Two Time Strings in Python. The datatime class provides a user with a number of functions to deal with dates and times in Python. The strptime() function is used to parse a string value to represent time based on a given format.

How does Python compare start time and end time?

Time Difference between two timestamps in Python First, store the start timestamp in the 'start' variable and the end timestamp in the 'end' variable. Next, use the fromtimestamp() method to convert both start and end timestamps to datetime objects.


1 Answers

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) 
like image 56
Daniel LeCheminant Avatar answered Sep 28 '22 07:09

Daniel LeCheminant