3

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.

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"?

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

benwebdev
  • 159
  • 9

5 Answers5

4

You could use a utility that will parse your weekday text into a System.DayOfWeek enumeration, example here. You can then use the Enum in a comparison against the DateTime.Now.DayOfWeek

Community
  • 1
  • 1
Lazarus
  • 41,906
  • 4
  • 43
  • 54
2

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);
}
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
1

You can use DayOfTheWeek property of the DateTime. 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.

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
1

This is very rough code, but illustrates that you can check a DateTime object containing the current time as you wish to do:

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

The DateTime object cannot handle a value that means all mondays. It would have to be a specific Monday. There is a DayOfWeek enumeration. Another object that may help you is a TimeSpan object. You could use the DayOfWeek combined with TimeSpan to tell you when to start, then use another TimeSpan to tell you how long

Seattle Leonard
  • 6,548
  • 3
  • 27
  • 37