Alex Rivera | Logout

Counting regular working days in a given period of time

Asked 2010-09-14T12:34:52.007
9

need some help. I need to count regular working days for a given date period, for example, in our country, we have 5 regular working days monday to friday, then in code i need to exclude saturdays and sundays when I use it on my computations.

I need an algorithm something like this in C#:

    int GetRegularWorkingDays(DateTime startDate, DateTime endDate)
    {

       int nonWorkingDays = ((endDate - startDate) % 7) * 2;

       return (endDate - startDate) - nonWorkingDays;
    }

I know my draft is way way off :(. Thanks in advance. =)

PS: Guys please up-vote the best/fastest/most efficient answer below. Thanks =)

Edit
Report

1 Answer

20

Check out this example on Code Project that uses a very efficient way that doesn't involve any looping and has C# and SQL Server implementations.

It uses this alogrithm:

  1. Calculate the number of time span in terms of weeks. Call it, W.
  2. Deduct the first week from the number of weeks. W= W-1
  3. Multiply the number of weeks with the number of working days per week. Call it, D.
  4. Find out the holidays during the specified time span. Call it, H.
  5. Calculate the days in the first week. Call it, SD.
  6. Calculate the days in the last week. Call it, ED.
  7. Sum up all the days. BD = D + SD + ED - H.

Here is the C# example:

public static double CalculateBDay(
    DateTime startDate, 
    DateTime EndDate, 
    int NoOfDayWeek, /* No of Working Day per week*/
    int DayType 
)
{
    double iWeek, iDays, isDays, ieDays;
    //* Find the number of weeks between the dates. Subtract 1 */
    // since we do not want to count the current week. * /
    iWeek =DateDiff("ww",startDate,EndDate)-1 ;
    iDays = iWeek * NoOfDayWeek;
    //
    if( NoOfDayWeek == 5)
    {
        //-- If Saturday, Sunday is holiday
        if ( startDate.DayOfWeek == DayOfWeek.Saturday ) 
            isDays = 7 -(int) startDate.DayOfWeek;
        else
            isDays = 7 - (int)startDate.DayOfWeek - 1;
    } 
    else
    {
        //-- If Sunday is only <st1:place>Holiday</st1:place>
        isDays = 7 - (int)startDate.DayOfWeek;
    }
    //-- Calculate the days in the last week. These are not included in the
    //-- week calculation. Since we are starting with the end date, we only
    //-- remove the Sunday (datepart=1) from the number of days. If the end
    //-- date is Saturday, corre
answered 2010-09-14T12:57:15.463

Your Answer