Calculation of business hours (including holidays) using the
Time Period Library for .NET[
^]:
public void CalculateBusinessHoursSample()
{
CalendarTimeRange testPeriod = new CalendarTimeRange(
new DateTime( 2011, 3, 1 ), new DateTime( 2011, 5, 1 ) );
Console.WriteLine( "period: {0}", testPeriod );
TimePeriodCollection holidays = new TimePeriodCollection();
Console.WriteLine( "business hours without holidays: {0}",
CalculateBusinessHours( testPeriod, holidays ) );
holidays.Add( new Day( 2011, 3, 9 ) ); Console.WriteLine( "business hours with holidays: {0}",
CalculateBusinessHours( testPeriod, holidays ) );
holidays.Add( new Days( 2011, 3, 16, 2 ) ); Console.WriteLine( "business hours with more holidays: {0}",
CalculateBusinessHours( testPeriod, holidays ) );
holidays.Add( new Week( 2011, 13 ) ); Console.WriteLine( "business hours with even more holidays: {0}",
CalculateBusinessHours( testPeriod, holidays ) );
}
public double CalculateBusinessHours( CalendarTimeRange testPeriod, ITimePeriodCollection holidays = null )
{
CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
filter.AddWorkingWeekDays(); filter.CollectingHours.Add( new HourRange( 8, 12 ) ); filter.CollectingHours.Add( new HourRange( 13, 18 ) ); if ( holidays != null )
{
filter.ExcludePeriods.AddAll( holidays );
}
CalendarPeriodCollector collector = new CalendarPeriodCollector(
filter, testPeriod );
collector.CollectHours();
double businessHours = 0.0;
foreach ( ICalendarTimeRange period in collector.Periods )
{
businessHours += Math.Round( period.Duration.TotalHours, 2 );
}
return businessHours;
}