Get the number of business days between two dates
Posted by gabriel,
Wed Aug 06 22:57:00 UTC 2008
Here’s a simple way of getting the number of business days between two dates using C#.
DateTime dtBegin = new DateTime(2008, 8, 6);
DateTime dtEnd = new DateTime(2008, 8, 13);
int dayCount = 0;
//while the End date is not reached
while (dtEnd.CompareTo(dtBegin) > 0)
{
//check if the day is not a weekend day
if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) && (dtBegin.DayOfWeek != DayOfWeek.Sunday))
{
dayCount++;
}
//go to next day
dtBegin = dtBegin.AddDays(1);
}
You can enhance this method consulting a list of holidays to check if the current date is indeed a business day. For this you have to have the list of holidays somewhere. In our example I’ll create a fake method that will provide the holidays list.
public static void CalculateNumberOfWeekdays()
{
DateTime dtBegin = new DateTime(2008, 8, 6);
DateTime dtEnd = new DateTime(2008, 8, 13);
List<DateTime> holidays = GetHolidays();
int dayCount = 0;
//while the End date is not reached
while (dtEnd.CompareTo(dtBegin) > 0)
{
//check if the day is not a weekend day
if ((dtBegin.DayOfWeek != DayOfWeek.Saturday)
&& (dtBegin.DayOfWeek != DayOfWeek.Sunday)
&& (!holidays.Contains(dtBegin)))
{
dayCount++;
}
//go to next day
dtBegin = dtBegin.AddDays(1);
}
Console.WriteLine(dayCount);
}
public static List<DateTime> GetHolidays()
{
List<DateTime> holidays = new List<DateTime>();
holidays.Add(new DateTime(2008, 8, 7));
return holidays;
}
See you next time.