Friday, August 18, 2006

Number of Week Days in a Date Range Function

I needed a graceful way to count the number of "week days" that existed in a given date range.  At least in the United States, a weekday is between Monday and Friday (i.e., Saturday and Sundays are weekends).

I looked through some of the common BCL objects, and Google'd a bit, but didn't find a pre-written solution (but, the way my afternoon is going, it could have been staring me in the face and I just didn't see it).

Here's a function that I whipped together.  I tried to make it flexible by using the DayOfWeek enumeration (in case another calendar might have a different set of Days of Week, etc) and allowing the definition of a "weekday" to be specified as any day between "wkStart" and "wkEnd" inclusive.

public int WeekDaysInDateRange(DateTime start, DateTime end)
{
int DaysInWeek = Enum.GetValues(typeof(DayOfWeek)).Length;

DayOfWeek wkStart = DayOfWeek.Monday;
DayOfWeek wkEnd = DayOfWeek.Friday;

// Adjust the start date to the first week day, if needed
if (start.DayOfWeek < wkStart)
{
start = start.AddDays((int)(wkStart - start.DayOfWeek));
}
else if (start.DayOfWeek > wkEnd)
{
start = start.AddDays(DaysInWeek - (int)start.DayOfWeek + (int)wkStart);
}

// Adjust the end date to the last week day, if needed
if (end.DayOfWeek > wkEnd)
{
end = end.AddDays((int)(wkEnd - end.DayOfWeek));
}

TimeSpan duration = (end - start).Duration(); // "Absolute value"

int wks = duration.Days / DaysInWeek;
int days = wks * ((int)(wkEnd - wkStart) + 1);

days += ((int)(end.DayOfWeek - start.DayOfWeek) + 1);

return days;
}

Anyone have a more graceful method?


tags: , , ,