简体   繁体   English

常规日期时间问题

[英]Regular DateTime question

I'm writing a service but I want to have config settings to make sure that the service does not run within a certain time window on one day of the week. 我正在写一个服务,但我想要配置设置,以确保服务不会在一周的某一天的特定时间窗口内运行。 eg Mondays between 17:00 and 19:00. 例如,周一17:00至19:00。

Is it possible to create a datetime that represents any monday so I can have one App config key for DontProcessStartTime and one for DontProcessEndTime with a values like "Monday 17:00" and "Monday 19:00"? 是否有可能创建一个表示任何星期一的日期时间,因此我可以为DontProcessStartTime提供一个App配置密钥,为DontProcessEndTime设置一个值为“Monday 17:00”和“Monday 19:00”的值?

Otherwise I assume I'll have to have separate keys for the day and time for start and end of the time window. 否则我假设我必须为时间窗口的开始和结束的日期和时间分别设置密钥。

Any thoughts? 有什么想法吗?

thanks 谢谢

You could use a utility that will parse your weekday text into a System.DayOfWeek enumeration, example here . 您可以使用一个实用程序将您的工作日文本解析为System.DayOfWeek枚举, 例如此处 You can then use the Enum in a comparison against the DateTime.Now.DayOfWeek 然后,您可以在与DateTime.Now.DayOfWeek进行比较时使用Enum

You can save the day of the week and start hour and endhour in your config file, and then use a function similar to the following: 您可以保存星期几并在配置文件中开始小时和结束时间,然后使用类似于以下内容的功能:

public bool ShouldRun(DateTime dateToCheck)
{
     //These should be read from your config file:
     var day = DayOfWeek.Monday;
     var start = 17;
     var end = 19;

     return !dateToCheck.DayOfWeek == day &&
            !(dateToCheck.Hour >= start && dateToCheck.Hour < end);
}

You can use DayOfTheWeek property of the DateTime . 您可以使用DateTime DayOfTheWeek属性。 And to check proper time you can use DateTime.Today (returns date-time set to today with time set to 00:00:00) and add to it necessary amount of hours and minutes. 并且要检查适当的时间,您可以使用DateTime.Today (将日期时间设置为今天,时间设置为00:00:00)并添加必要的小时和分钟数。

This is very rough code, but illustrates that you can check a DateTime object containing the current time as you wish to do: 这是非常粗略的代码,但说明您可以根据需要检查包含当前时间的DateTime对象:

protected bool IsOkToRunNow()
{
    bool result = false;

    DateTime currentTime = DateTime.Now;

    if (currentTime.DayOfWeek != DayOfWeek.Monday && (currentTime.Hour <= 17 || currentTime.Hour >= 19))
    {
        result = true;
    }

    return result;
}

The DateTime object cannot handle a value that means all mondays. DateTime对象无法处理意味着所有星期一的值。 It would have to be a specific Monday. 它必须是特定的星期一。 There is a DayOfWeek enumeration. 有一个DayOfWeek枚举。 Another object that may help you is a TimeSpan object. 可能对您有帮助的另一个对象是TimeSpan对象。 You could use the DayOfWeek combined with TimeSpan to tell you when to start, then use another TimeSpan to tell you how long 您可以使用DayOfWeek结合TimeSpan告诉您何时开始,然后使用另一个TimeSpan告诉您多长时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM