Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calculate Business Hours

0.00/5 (No votes)
13 Apr 2012 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here