Jorrit Reedijk - 10 days ago 5
Vb.net Question

# calculate date add, but only weekdays

I would like to calculate a new date simply by using the build-in dateadd function, but take into account that only weekdays should be counted (or 'business days' so to speak).

I have come up with this simple algorithm, which does not bother about holidays and such. I have tested this with some simple dates, but would like some input if this can be done in better ways.

This sample assumes a week with 5 business days, monday-friday, where first day of the week is monday. Dateformatting used here is d-m-yyyy, the sample calculates with a startdate of october 1, 2009.

Here is the simple form:

``````Dim d_StartDate As DateTime = "1-10-2009"
Dim i_NumberOfDays As Integer = 12
Dim i_CalculateNumberOfDays As Integer

If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then
i_CalculateNumberOfDays = i_NumberOfDays
Else
i_CalculateNumberOfDays = i_NumberOfDays + (Int(((i_NumberOfDays + (7 - d_StartDate.DayOfWeek)) / 5)) * 2)
End If

``````

Which I try to explain with the following piece of code:

``````''' create variables to begin with
Dim d_StartDate as Date = "1-10-2009"
Dim i_NumberOfDays as Integer = 5

''' create var to store number of days to calculate with

''' amount of businessdays left in the week of the startdate
If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then

''' start by substracting days in week with the current day,
''' to calculate the remainder of days left in the current week

''' add the remainder of days in this week to the total
''' number of days we have to add to the date

''' divide by 5, because we need to know how many
''' business weeks we are dealing with

''' multiply the integer of current business weeks by 2
''' those are the amount of days in the weekends we have
''' to add to the total

''' add the number of days to the weekend days

Else

''' there are enough businessdays left in this week
''' to add the given amount of days

End If

''' this is the numberof dates to calculate with in DateAdd
dim d_CalculatedDate as Date
``````

Your plan seems like it should work. Make sure you wrap it in a function instead of doing out the calculations every place you use it so that if/when you discover you need to account for holidays, you don't have to change it in tons of places.

The best way I can think of for implementing support for holidays would be to add days one at a time in a loop. Each iteration, check if its a weekend or a holiday, and if it is add another day and continue (to skip it). Below is an example in pseudocode (I don't know VB); no guarantees its correct. Of course, you need to provide your own implementations for isWeekend() and isHoliday().

``````function addBusinessDays(startDate, numDays)
{
Date newDate = startDate;
while (numDays > 0)
{