VB.NET - counting days between two dates with exclusions

Isuru picture Isuru · Jan 29, 2012 · Viewed 10.9k times · Source

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

Answer

Dennis Traub picture Dennis Traub · Jan 29, 2012
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