VB.NET - counting days between two dates with exclusions

11,120

Solution 1

Dim count = 0
Dim totalDays = (dtpEndDate - dtpStartDate).Days

For i = 0 To totalDays
    Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
    If weekday <> DayOfWeek.Saturday AndAlso weekday <> DayOfWeek.Sunday Then
        count += 1
    End If
Next

lblNoOfDays.Text = count

Solution 2

This function calculates the non-weekend days between two dates:

    Public Shared Function WorkingDaysElapsed(ByVal pFromDate As Date, ByVal pToDate As Date) As Integer

        Dim _elapsedDays As Integer = 0
        Dim _weekendDays As DayOfWeek() = {DayOfWeek.Saturday, DayOfWeek.Sunday}

        For i = 0 To (pToDate - pFromDate).Days
            If Not _weekendDays.Contains(pFromDate.AddDays(i).DayOfWeek) Then _elapsedDays += 1
        Next

        Return _elapsedDays

    End Function
Share:
11,120
Isuru
Author by

Isuru

Started out as a C# developer. Turned to iOS in 2012. Currently learning SwiftUI. Loves fiddling with APIs. Interested in UI/UX. Want to try fiddling with IoT. Blog | LinkedIn

Updated on June 14, 2022

Comments

  • Isuru
    Isuru almost 2 years

    I'm trying to count the days between two dates, excluding Saturdays and Sundays. I've written this code so far

    Dim startDay As Integer
    Dim endDay As Integer
    Dim days As Integer
    Dim count As Integer
    
    startDay = dtpStartDate.Value.DayOfWeek
    endDay = dtpEndDate.Value.DayOfWeek
    
    For days = startDay To endDay
        If days = 0 Or days = 6 Then           'Sunday = 0, Saturday = 6
            count += 1
        End If
    Next
    
        lblNoOfDays.Text = count
    

    It works fine if you choose the two dates within the same week. (ex: 23rd Jan to 27th Jan, gives the result 5) But if I set them to dates in different weeks, (ex : 23rd Jan to 30th Jan, gives the result 1), it gives incorrect results.

    I know it happens because of the loop but I can't think of a way to overcome this. Can anyone give me a suggestion, solution??

    Thank you