如果当前时间是在时间框架之间

如果当前时间是在时间框架之间

本文介绍了如何检查,如果当前时间是在时间框架之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户可以配置在非高峰时段运行的服务。他们有规定的时限,该服务可以运行的能力。

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.

例如:

用户A的工作原理8点至晚5,所以他们要安排应用至下午5:30和7:30之间运行。

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

用户B工作9 pm-6am,所以他们安排应用上午6:30和下午8:30之间运行。

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.

鉴于当前时间的日期时间,开始日期时间和停止时间的DateTime,我怎么能检查电流之间开始和停止。

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.

推荐答案

如果的startTime 结束时间重新present一个单一的时间间隔(它只会发生一次,而的startTime 结束时间重新present日期和启动/停止的时间),那么它的话说

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;

如果这是一个反复出现的事件(每天都是这样,有的间隔内),您可以使用做比较的<$c$c>TimeOfDay属性。 (反复出现的情况是一个,你必须考虑的一个开始/停止跨越午夜)

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

}

(注:此code假定,如果开始==结束,那么它涵盖了所有次你做了一个评论在另一个帖子这个效果。)

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

例如,要检查它是否是上午5点和下午9:30之间

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))

如果的startTime 结束时间的DateTime S,你可以说

If startTime and endTime are DateTimes, you could say

IsTimeOfDayBetween(someTime, startTime.TimeOfDay, endTime.TimeOfDay)

这篇关于如何检查,如果当前时间是在时间框架之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:43