Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if current day is working day

Tags:

c#

I have application that needs to be run on working days, and within working hours.

In application configuration, I've set start time in format

Monday-Friday
9:00AM-5:30PM

Now, I have a problem how to check if current day is within day boundare is (for the time is easy - parse time with DateTime.ParseExact and simple branch will do), but I don't know how to parse days.

I've tried with:

DayOfWeek day = DateTime.Now.DayOfWeek;
if (day >= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day) &&
    day <= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day))
{ /* OK */ }

sr.start_day and sr.end_day are strings

but the problem occurred during weekend testing - apparently, in DayOfWeek enum, Sunday is first day of the week (refering to the comments on MSDN page

I suppose I could do some gymnastics with current code, but I am looking for the most readable code available.

Edit Sorry for the misunderstanding - working days are not from Monday to Friday - they are defined as strings in config file, and they can be even from Friday to Saturday - which breaks my original code.

like image 878
Nemanja Boric Avatar asked Jul 15 '12 19:07

Nemanja Boric


2 Answers

if ((day >= DayOfWeek.Monday) && (day <= DayOfWeek.Friday))
{
    // action
}
like image 98
Hogan Avatar answered Oct 19 '22 10:10

Hogan


From Hans Passant's comment on my original question:

Just add 7 to the end day if it is less than the start day. Similarly, add 7 to day if it is less than the start day.

DayOfWeek day = DateTime.Now.DayOfWeek;
DayOfWeek start_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day);
DayOfWeek end_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day);

if (end_day < start_day)
    end_day += 7;

if (day < start_day)
    day += 7;

if (day >= start_day && day <= end_day)
{ 
   //Action
}
like image 33
Nemanja Boric Avatar answered Oct 19 '22 10:10

Nemanja Boric