Link to home
Start Free TrialLog in
Avatar of Mike_Stevens
Mike_StevensFlag for United States of America

asked on

Determine date excluding weekends using VB.NET

I need to determine what the date (excuding weekends) will be based on a number using visual studio.

As a example: "What with the date be 5 business days from today".  the number days "5" will be a value that changes.  

I am sure this can be done but and not sure how.  I am using VB.NET in a Windows forms application.


Avatar of abel
abel
Flag of Netherlands image

If you don't need to account for banking holidays, which are different in each country and I wouldn't know yours, the easiest to do is to simply make the number higher, by doing this:

Dim realDays as Integer = CInt(businessDays / 5) * 7

this gives an approximate amount of real days. You can make that more precise by checking how far away the first weekend is and whether you are spanning an extra weekend like that. If you want I can extend that little code line for you to accompany that.
I was a bit too eager there. Maybe it can be done so easily, but I couldn't make a reliable version myself, and I figured you may want to use the holidays at some point. Below is a function that works and you can easily extend it to include any other holdiays (1st of January etc) in the loop:

Dim businessDays = 12
Dim countDays As Integer = 0
Dim today As DateTime = DateTime.Today
 
Do While businessDays > 0
    countDays += 1
    Dim weekDay As DayOfWeek = today.AddDays(countDays).DayOfWeek
    If weekDay <> DayOfWeek.Saturday And weekDay <> DayOfWeek.Sunday Then
        businessDays -= 1
    End If
Loop
Debug.WriteLine("Calculated days: " & countDays & ", original days: " & businessDays)

Open in new window

The above function will be quick for even if the amount of days are a few centuries from each other.
Avatar of Mike_Stevens

ASKER

I am not sure if this is what I a looking for.  As an example:  "I need to know what the date will be 5 business days from now".   Not the number days.


well, that's closely the same... But you are right of course, I only showed you how to get the number of days. Here's the same example, wrapped inside a method, that returns the date:

Private Function GetDateByBusinessDays(ByVal dateFrom As DateTime, ByVal businessDays As Integer) As DateTime
    Dim countDays As Integer = 0
 
    Do While businessDays > 0
        countDays += 1
        Dim weekDay As DayOfWeek = dateFrom.AddDays(countDays).DayOfWeek
        If weekDay <> DayOfWeek.Saturday And weekDay <> DayOfWeek.Sunday Then
            businessDays -= 1
        End If
    Loop
    Return dateFrom.AddDays(countDays)
End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of abel
abel
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes....that output is what I am looking for.  Thanks.
You're welcome :)