2012-08-29

How many times does a day occur within a date range?

Given two dates I need to know how many times each day of the week occurs within that range, so that I can calculate a value where the factor varies by day.  So I wrote the following code which returns an array of integers, position 0 will tell you how many Sundays there are, position 6 will tell you how many Saturdays, and so on.

int[] CountDays(DateTime firstDate, DateTime lastDate)
{
var totalDays
= lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;
var weeks
= (int)Math.Floor(totalDays / 7);

var result
= Enumerable.Repeat<int>(weeks, 7).ToArray();
if (totalDays % 7 != 0)
{
int firstDayOfWeek = (int)firstDate.DayOfWeek;
int lastDayOfWeek = (int)lastDate.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek
+= 7;
for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)
result[dayOfWeek
% 7]++;
}
return result;
}

No comments: