Common DateTime Question

I am writing a service, but I want to have configuration settings to make sure that the service does not start for a certain time on one day of the week. for example, from Monday from 17:00 to 19:00.

Is it possible to create a date-time representing any Monday, so I can have one application key for DontProcessStartTime and one for DontProcessEndTime with values ​​such as "Monday 17:00" and "Monday 19:00"?

Otherwise, I assume that for the beginning and end of the time window I will have to have separate keys for the day and time.

Any thoughts?

thank

+3
source share
5 answers

, System.DayOfWeek, . Enum DateTime.Now.DayOfWeek

+4

, , :

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);
}
+2

DayOfTheWeek DateTime. , DateTime.Today ( -, , , 00:00:00) .

+1

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

The object DateTimecannot process a value meaning all Mondays. It was supposed to be a specific Monday. There is an enumeration DayOfWeek. Another object that can help you is the object TimeSpan. You can use DayOfWeekin conjunction with TimeSpanto tell you when to start, and then use another TimeSpanto tell you how long

+1
source

Source: https://habr.com/ru/post/1772147/


All Articles