Click here to Skip to main content

Calculate Business Hours

Method to find out business hours in between two dates. public static double CalculateBusinessHours(DateTime dtStart, DateTime dtEnd) { int StartingHour = 9; int EndingHour = 18; // initialze our return value double OverAllMinutes = 0.0; ...
Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment
See more: C#
Method to find out business hours in between two dates.
 
 public static double CalculateBusinessHours(DateTime dtStart, DateTime dtEnd)
    {
        int StartingHour = 9;
        int EndingHour = 18;
 
        // initialze our return value
        double OverAllMinutes = 0.0;
 
        // start time must be less than end time
        if (dtStart > dtEnd)
        {
            return OverAllMinutes;
        }
        DateTime ctTempEnd = new DateTime(dtEnd.Year, dtEnd.Month, dtEnd.Day, 0, 0, 0);
        DateTime ctTempStart = new DateTime(dtStart.Year, dtStart.Month, dtStart.Day, 0, 0, 0);
 
        // check if startdate and enddate are the same day
        bool bSameDay = (ctTempStart == ctTempEnd);
 
        // calculate the business days between the dates
        int iBusinessDays = GetBusinessDays(ctTempStart, ctTempEnd);
 
        // now add the time values to our temp times
        TimeSpan CTimeSpan = new TimeSpan(0, dtStart.Hour, dtStart.Minute, 0);
        ctTempStart += CTimeSpan;
        CTimeSpan = new TimeSpan(0, dtEnd.Hour, dtEnd.Minute, 0);
        ctTempEnd += CTimeSpan;
 
        // set our workingday time range and correct the first day
        DateTime ctMaxTime = new DateTime(ctTempStart.Year, ctTempStart.Month, ctTempStart.Day, EndingHour, 0, 0);
        DateTime ctMinTime = new DateTime(ctTempStart.Year, ctTempStart.Month, ctTempStart.Day, StartingHour, 0, 0);
        Int32 FirstDaySec = CorrectFirstDayTime(ctTempStart, ctMaxTime, ctMinTime);
 
        // set our workingday time range and correct the last day
        DateTime ctMaxTime1 = new DateTime(ctTempEnd.Year, ctTempEnd.Month, ctTempEnd.Day, EndingHour, 0, 0);
        DateTime ctMinTime1 = new DateTime(ctTempEnd.Year, ctTempEnd.Month, ctTempEnd.Day, StartingHour, 0, 0);
        Int32 LastDaySec = CorrectLastDayTime(ctTempEnd, ctMaxTime1, ctMinTime1);
        Int32 OverAllSec = 0;
 
        // now sum-up all values
        if (bSameDay)
        {
            if (iBusinessDays != 0)
            {
                TimeSpan cts = ctMaxTime - ctMinTime;
                Int32 dwBusinessDaySeconds = (cts.Days * 24 * 60 * 60) + (cts.Hours * 60 * 60) + (cts.Minutes * 60) + cts.Seconds;
                OverAllSec = FirstDaySec + LastDaySec - dwBusinessDaySeconds;
            }
        }
        else
        {
            if (iBusinessDays > 1)
                OverAllSec =
                ((iBusinessDays - 2) * 9 * 60 * 60) + FirstDaySec + LastDaySec;
        }
        OverAllMinutes = OverAllSec / 60;
 
        return OverAllMinutes / 60;
 

    }
 
This method uses following functions.
 
 public static DateTime AddBusinessDays(DateTime dt, int nDays)
    {
        int weeks = nDays / 5;
        nDays %= 5;
        while (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
            dt = dt.AddDays(1);
 
        while (nDays-- > 0)
        {
            dt = dt.AddDays(1);
            if (dt.DayOfWeek == DayOfWeek.Saturday)
            {
                dt = dt.AddDays(2);
            }
        }
        return dt.AddDays(weeks * 7);
    }
 
    private static int GetBusinessDays(DateTime ctStart, DateTime ctEnd)
    {
        TimeSpan ctp = ctEnd - ctStart;
        int iDays = ctp.Days + 1;
        int iWeeks = iDays / 7;
        int iBusDays = iWeeks * 5;
        int iRem = iDays % 7;
        while (iRem > 0)
        {
            // no sunday, no saturday
            int iStartDay = (Int32)Enum.Parse(typeof(DayOfWeek), ctStart.DayOfWeek.ToString());
            if (iStartDay != 1 && iStartDay != 7)
            {
                iBusDays++;
            }
            TimeSpan time1 = new TimeSpan(1, 0, 0, 0);
            ctStart += time1;
 
            iRem--;
        }
        return iBusDays;
    }
 
    private static Int32 CorrectFirstDayTime(DateTime ctStart, DateTime ctMaxTime, DateTime ctMinTime)
    {
        Int32 daysec = 0;
 
        if (ctMaxTime < ctStart) // start time is after max time
        {
            return 0; // zero seconds for the first day
        }
        int iStartDay = (Int32)Enum.Parse(typeof(DayOfWeek), ctStart.DayOfWeek.ToString());
        if (iStartDay == 1 && iStartDay == 7)
        {
            return 0;
        }
        if (ctStart < ctMinTime) // start time is befor min time
        {
            ctStart = ctMinTime; // set start time to min time
        }
        TimeSpan ctSpan = ctMaxTime - ctStart;
        daysec = (ctSpan.Days * 24 * 60 * 60) + (ctSpan.Hours * 60 * 60) + (ctSpan.Minutes * 60) + ctSpan.Seconds;
        return daysec;
    }
    private static Int32 CorrectLastDayTime(DateTime ctEnd, DateTime ctMaxTime, DateTime ctMinTime)
    {
        Int32 daysec = 0;
 
        if (ctMinTime > ctEnd) // start time is after max time
        {
            return 0; // zero seconds for the first day
        }
        int iEndDay = (Int32)Enum.Parse(typeof(DayOfWeek), ctEnd.DayOfWeek.ToString());
        if (iEndDay == 1 && iEndDay == 7)
        {
            return 0;
        }
        if (ctEnd > ctMaxTime) // start time is befor min time
        {
            ctEnd = ctMaxTime; // set start time to min time
        }
        TimeSpan ctSpan = ctEnd - ctMinTime;
        daysec = (ctSpan.Days * 24 * 60 * 60) + (ctSpan.Hours * 60 * 60) + (ctSpan.Minutes * 60) + ctSpan.Seconds;
        return daysec;
    }
Posted 8 Feb '10
Edited 23 Feb '10


Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Alternative 1

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
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Your Filters
Interested
Ignored
     
  1. SAKryukov (473)
  2. Rahul Dhoble (200)
  1. SAKryukov (9,507)
  2. Christian Graus (5,960)
  3. OriginalGriff (4,663)
  4. Abhinav S (4,335)
  5. thatraja (4,269)

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThis is perle1's algorithm converted to C# Pinmemberu166227:59 9 Dec '10  
GeneralJust a question PinmemberThe Manoj Kumar15:22 16 Mar '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.


Advertise | Privacy | Mobile
Web04 | 2.5.120210.1 | Last Updated 25 Mar 2011
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid