Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...