How to Calculate number of weekend days between the two dates?

# How to Calculate number of weekend days between the two dates?

• Thursday, August 17, 2006 5:39 PM

If start date is 08/17/2006 (17th august) and end date is 08/29/2006 the total number of weekend days are 4

### All Replies

• Thursday, August 17, 2006 6:35 PM

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim BeginDate As Date = New Date(2006, 8, 16)

Dim EndDate As Date = New Date(2006, 8, 28)

MsgBox("Weekend days:" & CountWeekEnds(BeginDate, EndDate).ToString)

End Sub

Private Function CountWeekEnds(ByVal BeginDate As Date, ByVal EndDate As Date) As Integer

Dim Days As Integer

Do While BeginDate < EndDate

If BeginDate.DayOfWeek = DayOfWeek.Saturday OrElse BeginDate.DayOfWeek = DayOfWeek.Sunday Then

Days += 1

End If

Loop

Return Days

End Function

• Thursday, August 17, 2006 6:45 PM
Moderator

Or a non looping suggestion:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

MessageBox.Show(GetWeekEndDays(Me.DateTimePicker1.Value, Me.DateTimePicker2.Value))

End Sub

Public Function GetWeekEndDays(ByVal SD As Date, ByVal ED As Date) As Integer

Dim DaysDiff As Integer = DateDiff(DateInterval.Day, SD, ED)

Dim NumWeekEndDays As Integer

NumWeekEndDays = CInt((DaysDiff / 7) * 2)

If SD.DayOfWeek = DayOfWeek.Saturday Or SD.DayOfWeek = DayOfWeek.Sunday _

Or ED.DayOfWeek = DayOfWeek.Saturday Or ED.DayOfWeek = DayOfWeek.Sunday Then

NumWeekEndDays += 1

End If

Return NumWeekEndDays

End Function

• Thursday, August 17, 2006 6:54 PM

Anyone know why the code doesn't format properly?
• Thursday, August 17, 2006 6:59 PM

Depending on your requirements, you may need to change the < to <= in my do loop.
• Thursday, August 17, 2006 7:00 PM

DMan1 your solution is not generating right result?
• Thursday, August 17, 2006 7:53 PM
Moderator

I did test the code...Can you please give me sample dates that would produce errouneous results?

Even if I reversed the dats I am getting a negitive but the actual number of weekend days seems to be correct...but the proof is in the pudding...all we need is one sample where it produces the wrong answer

• Thursday, August 17, 2006 8:09 PM

Can you please give me sample dates that would produce errouneous results?

8/26/06 - 8/27/06.