I need to count the total days worked given struct saying which days of the week are worked and a from and to date.
My current algorithm is this:
protected int TotalWorkDays(DateTime From, DateTime dtTo,WorkedDays days)
{
int Days = 0;
DayOfWeek DOW;
for (DateTime curDate = From; curDate.Date <= dtTo.Date; curDate = curDate.AddDays(1))
{
DOW = curDate.DayOfWeek;
if ((DOW == DayOfWeek.Sunday & days.Sunday) |
(DOW == DayOfWeek.Monday & days.Monday) |
(DOW == DayOfWeek.Tuesday & days.Tuesday) |
(DOW == DayOfWeek.Wednesday & days.Wednesday) |
(DOW == DayOfWeek.Thursday & days.Thursday) |
(DOW == DayOfWeek.Friday & days.Friday) |
(DOW == DayOfWeek.Saturday & days.Saturday)
)
{
Days += 1;
}
}
return Days;
}
I’m almost positive this can be done without a loop, but I can’t seem to figure out. Can someone help me find a more efficient algorithm?
Find the number of weeks between the From and To dates (using subtraction and division). Then multiply that by the number of days worked per week. Do some subtraction for the end cases (From/To dates are in the middle of a week).