Find the count of a weekday between two dates without iterating/looping
I like things simple for debugging purposes... LINQ implies a list or some iterable thing, but that's just me. I think this works:static int CountDayOcurrence(DateTime start, DateTime end, DayOfWeek day){ var wstart = start.AddDays(7 - (int) start.DayOfWeek); // Sunday after start...
I like things simple for debugging purposes... LINQ implies a list or some iterable thing, but that's just me. I think this works:
static int CountDayOcurrence(DateTime start, DateTime end, DayOfWeek day)
{
var wstart = start.AddDays(7 - (int) start.DayOfWeek); // Sunday after start date
var wend = end.AddDays(-(int)end.DayOfWeek); // Sunday before end
var ocurrences = (wend - wstart).Days / 7; // complete weeks (Sunday through Sunday)
if (start.DayOfWeek <= day) //
ocurrences++;
if (end.DayOfWeek >= day)
ocurrences++;
return ocurrences;
}