65.9K
CodeProject is changing. Read more.
Home

Calculate Business Hours

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (8 votes)

Apr 13, 2012

CPOL
viewsIcon

44003

Calculation of business hours (including holidays) using the Time Period Library for .NET

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 );
  // > period: 01.03.2011 00:00:00 - 30.04.2011 23:59:59 | 60.23:59

  TimePeriodCollection holidays = new TimePeriodCollection();
  Console.WriteLine( "business hours without holidays: {0}", 
    CalculateBusinessHours( testPeriod, holidays ) );
  // > business hours without holidays: 396

  holidays.Add( new Day( 2011, 3, 9 ) );       // day 3/9/2011
  Console.WriteLine( "business hours with holidays: {0}", 
    CalculateBusinessHours( testPeriod, holidays ) );
  // > business hours with holidays: 387

  holidays.Add( new Days( 2011, 3, 16, 2 ) );  // days 16/9/2011 and 17/9/2011
  Console.WriteLine( "business hours with more holidays: {0}", 
    CalculateBusinessHours( testPeriod, holidays ) );
  // > business hours with more holidays: 369

  holidays.Add( new Week( 2011, 13 ) );        // w/c 13 2011
  Console.WriteLine( "business hours with even more holidays: {0}", 
    CalculateBusinessHours( testPeriod, holidays ) );
  // > business hours with even more holidays: 324
} // CalculateBusinessHoursSample

// ----------------------------------------------------------------------
public double CalculateBusinessHours( CalendarTimeRange testPeriod, ITimePeriodCollection holidays = null )
{
  CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
  filter.AddWorkingWeekDays(); // only working days
  filter.CollectingHours.Add( new HourRange( 8, 12 ) );  // opening hours morning
  filter.CollectingHours.Add( new HourRange( 13, 18 ) ); // opening hours afternoon
  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;
} // CalculateBusinessHours