如何检查当前时间是否在一段时间之间? [英] How can I check if the current time is between in a time frame?
问题描述
我有一个用户可以配置为在非高峰时段运行的服务。他们有能力设置服务可以运行的时间。
例如:
用户A上午8点到下午5点,所以他们想安排应用程序在下午5:30到7:30之间运行。
用户B上午9点至下午6点,所以他们安排应用程序在上午6:30和晚上8:30之间运行。
$ b $关键是应用程序在不使用计算机的情况下使用它们。
给定当前时间的DateTime,启动的DateTime和停止时间的DateTime,如何检查当前是否在启动和停止之间。 p>
对我来说,棘手的部分是时间可以跨越午夜边界。
如果 startTime
和 endTime
表示单个时间间隔(只会发生一次,而$ code> startTime 和 endTime
表示开始/停止的日期和时间),那么简单说说
bool isTimeBetween = someTime> = startTime&& someTime< = endTime;
如果这是一个重复的事件(每隔一段时间发生),您可以使用 TimeOfDay
属性。 (经常发生的情况是你必须考虑到午夜的开始/停止)
static public bool IsTimeOfDayBetween(DateTime时间,
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;
}
}
(注意:此代码假定如果 start == end
,那么它覆盖所有的时间,你对另一个帖子发表了评论)
例如,检查是否在上午5点到晚上9点之间
IsTimeOfDayBetween(someTime,new TimeSpan(5,0 ,0),新的TimeSpan(21,30,0))
如果 startTime
和 endTime
是 DateTime
s,你可以说
IsTimeOfDayBetween(someTime,startTime.TimeOfDay,endTime.TimeOfDay)
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.
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 DateTime
s, you could say
IsTimeOfDayBetween(someTime, startTime.TimeOfDay, endTime.TimeOfDay)
这篇关于如何检查当前时间是否在一段时间之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!