Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting regular working days in a given period of time

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 =)

like image 316
CSharpNoob Avatar asked Sep 14 '10 12:09

CSharpNoob


1 Answers

Check out this example on Code Project that uses a very efficient way that doesn't involve any looping ;)

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.
like image 51
Iain Ward Avatar answered Sep 23 '22 10:09

Iain Ward