Excel provides the function
NetworkDays[^] for the calculation of working days within a time period.
This sample uses the
Time Period Library for .NET[
^], to imitate this function in C#.
Additional, the sample allows to consider multiple holiday-periods:
public void NetworkDaysSample()
{
DateTime start = new DateTime( 2011, 3, 1 );
DateTime end = new DateTime( 2011, 5, 1 );
Console.WriteLine( "period: {0}", new CalendarTimeRange( start, end ) );
Console.WriteLine( "network days without holidays: {0}",
NetworkDays( start, end ) );
List<DateTime> holidays = new List<DateTime>();
holidays.Add( new DateTime( 2011, 3, 9 ) );
holidays.Add( new DateTime( 2011, 3, 16 ) );
holidays.Add( new DateTime( 2011, 3, 17 ) );
Console.WriteLine( "network days with holidays: {0}",
NetworkDays( start, end, holidays ) );
TimePeriodCollection holidayPeriods = new TimePeriodCollection();
holidayPeriods.Add( new Week( 2011, 13 ) );
Console.WriteLine( "network days with holidays and holiday-periods: {0}",
NetworkDays( start, end, holidays, holidayPeriods ) );
}
public double NetworkDays( DateTime start, DateTime end,
IEnumerable<DateTime> holidays = null,
ITimePeriodCollection holidayPeriods = null )
{
Day startDay = new Day( start < end ? start : end );
Day endDay = new Day( end > start ? end : start );
if ( startDay.Equals( endDay ) )
{
return 0;
}
CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
filter.AddWorkingWeekDays();
if ( holidays != null )
{
foreach ( DateTime holiday in holidays )
{
filter.ExcludePeriods.Add( new Day( holiday ) );
}
}
if ( holidayPeriods != null )
{
filter.ExcludePeriods.AddAll( holidayPeriods );
}
CalendarTimeRange testPeriod = new CalendarTimeRange( start, end );
CalendarPeriodCollector collector =
new CalendarPeriodCollector( filter, testPeriod );
collector.CollectDays();
double networkDays = 0.0;
foreach ( ICalendarTimeRange period in collector.Periods )
{
networkDays += Math.Round( period.Duration.TotalDays, 2 );
}
return networkDays;
}