Calculating working days between 2 dates
Here is a function to calculate the number of working days given two dates. It assume the working days is from Monday to Friday, both dates are inclusive and no holidays in between.
static int CalculateWorkingDays(DateTime start, DateTime end)
{
DateTime firstSunday, lastSaturday;
int workDays = 0;
if (start.DayOfWeek != DayOfWeek.Sunday)
{
firstSunday = start.AddDays(7 - ((int)start.DayOfWeek));
workDays += (6 - (int)start.DayOfWeek);
}
else
firstSunday = start;
if (end.DayOfWeek != DayOfWeek.Saturday)
{
lastSaturday = end.AddDays(-((int)end.DayOfWeek) - 1);
workDays += (int)end.DayOfWeek;
}
else
lastSaturday = end;
TimeSpan ts = lastSaturday.Subtract(firstSunday);
workDays += ((ts.Days + 1) / 7) * 5;
return workDays;
}
Labels: programming