Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Date Compare: Count the amount of working days since a date?

What's the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay.

And by "working days", I mean all days excluding Saturday and Sunday. If the algorithm can also take into account a list of specific 'exclusion' dates that shouldn't count as working days, that would be gravy.

Thanks in advance for the contributed genius.

like image 575
Matias Nino Avatar asked Oct 03 '08 06:10

Matias Nino


People also ask

How do you count business days?

Business days are the weekdays Monday through Friday. Check Business Days Only to exclude weekend days in your calendar calculation. Check Saturday is a Business Day to include Saturdays. Holidays are not included in the calculation.

How do I get the difference between two dates in C#?

The difference between two dates can be calculated in C# by using the substraction operator - or the DateTime. Subtract() method. The following example demonstrates getting the time interval between two dates using the - operator.


2 Answers

Here is a sample of Steve's formula in VB without the holiday subtraction:

Function CalcBusinessDays(ByVal DStart As Date, ByVal DEnd As Date) As Decimal

        Dim Days As Decimal = DateDiff(DateInterval.Day, DStart, DEnd)
        Dim Weeks As Integer = Days / 7
        Dim BusinessDays As Decimal = Days - (Weeks * 2)
        Return BusinessDays
        Days = Nothing
        Weeks = Nothing
        BusinessDays = Nothing

End Function
like image 183
Chris Betlach Avatar answered Sep 27 '22 18:09

Chris Betlach


in general (no code) -

  • subtract the dates to get the number of days
  • divide by 7 to get the number of weeks
  • subtract number of weeks times 2
  • count the number of holiday dates that fall with the date range
  • subtract that count

fiddle with the start/end dates so that they fall monday to monday, then add back the difference

[apologies for the no-code generalities, it's late]

[c.f. endDate.Subtract(startDate).TotalDays]

like image 26
Steven A. Lowe Avatar answered Sep 27 '22 18:09

Steven A. Lowe