In C#, how can I calculate the number of business (or weekdays) days between two dates?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Well this has been beaten to death. :) However I'm still going to provide another answer because I needed something a bit different. This solution is different in that it returns a Business TimeSpan between the start and end, and you can set the business hours of the day, and add holidays. So you can use it to calculate if it happens within a day, across days, over weekends, and even holidays. And you can get just the business days or not by just getting what you need from the returned TimeSpan object. And the way it uses lists of days, you can see how very easy it would be to add the list of non-work days if it's not the typical Sat and Sun. And I tested for a year, and it seems super fast.
I just hope the pasting of the code is accurate. But I know it works.
And here is test code: Note that you just have to put this function in a class called DateHelper for the test code to work.
This is a generic solution.
startdayvalue is day number of start date.
weekendday_1 is day numner of week end.
day number - MON - 1, TUE - 2, ... SAT - 6, SUN -7.
difference is difference between two dates..
Example : Start Date : 4 April, 2013, End Date : 14 April, 2013
Difference : 10, startdayvalue : 4, weekendday_1 : 7 (if SUNDAY is a weekend for you.)
This will give you number of holidays.
No of business day = (Difference + 1) - holiday1
I searched a lot for a, easy to digest, algorithm to calculate the working days between 2 dates, and also to exclude the national holidays, and finally I decide to go with this approach:
Basically I wanted to go with each date and evaluate my conditions:
but also I wanted to avoid iterating dates.
By running and measuring the time need it to evaluate 1 full year, I go the following result:
I know this question is already solved, but I thought I could provide a more straightforward-looking answer that may help other visitors in the future.
Here's my take at it:
This was my original submission:
I was having trouble finding a solid TSQL version of this code. Below is essentially a conversion of the C# code here with addition of the Holiday table which should be used to pre-calculate holidays.
I believe this could be a simpler way: