views:

55

answers:

5

Hi,

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

+1  A: 

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
+3  A: 

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

Lazarus
There is Enum.TryParse generic method in .NET 4.0
Andrew Bezzub
@Andrew Bezzub - Good to know, great comment!
Lazarus
In case you are not using .NET 4.0 the DateTime struct also has a TryParse method.
Fischer
@Fischer - Would DateTime.TryParse extract anything useful out of "Monday 17:00"?
Lazarus
I am not sure of that, I expect it is necessary to do some preprocessing. It was just as an alternative to the .NET 4.0 Enum.Parse method.
Fischer
+1  A: 

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;
}
Matthew Graybosch
+1  A: 

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);
}
klausbyskov
+1  A: 

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