How to count weekend days between two dates
This VB.NET method returns the total number of weekend days between two dates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Public Function CountWeekendDays(ByVal FromDate As Date, ByVal ToDate As Date)
Dim TotalDaysInt As Integer = ToDate.Date.Subtract(FromDate.Date).Days
Dim WeeksInt As Integer = Math.Floor(TotalDaysInt / 7)
Dim WeekendDaysInt As Integer = WeeksInt * 2
If TotalDaysInt Mod 7 <> 0 Then
If FromDate.DayOfWeek = DayOfWeek.Sunday Then
WeekendDaysInt += 1
Else
Dim SaturdayOffsetInt = Math.Max((TotalDaysInt Mod 7) - (DayOfWeek.Saturday - FromDate.DayOfWeek), 0)
WeekendDaysInt += Math.Min(SaturdayOffsetInt, 2)
End If
End If
Return WeekendDaysInt
End Function |
It works by multiplying the number of full weeks by 2, then it takes the leftover days and calculates how many of those days overlap the weekend.
For example:
Sunday = 0, Monday = 1, Tuesday = 2 …(and so on)
Let’s say FromDate is Wednesday, and the total number of days to ToDate is 18:
FromDate = Wednesday = 3
TotalDays = 18
TotalWeeks = Math.Floor(18 / 7) = 2
LeftoverDays = (TotalDays Mod 7) = (TodalDays – (TotalWeeks * 7)) = 4
DaysUntilSaturday = (Saturday – CheckInDate) = (6 – 3) = 3
DaysThatOverlapSaturday = (LeftoverDays – DaysUntilSaturday) = (4 – 3) = 1
Saturday is overlapped by 1 day, so we add 1 to the total number of weekend days.
WeekendDays = ((TotalWeeks * 2) + DaysThatOverlapSaturday) = (4 + 1) = 5
Of course if DaysThatOverlapSaturday < 1, don’t add anything.
If TotalDays = 19, then there would be 2 days that overlap Saturday. Since we know Sunday is the next day, we add both days.
If TotalDays = 20, then there would be 3 days that overlap Saturday, but that third day is Monday, so we only add 2.
If TotalDays = 21, then that’s 3 full weeks, and we know that 3 full weeks will always contain 6 weekend nights, so there’s nothing more to do.
The only other case is if the total number of days aren’t divisible by 7 and the Check-In date is Sunday. Since we know the remaining number of days are less then 7, we only have to add 1 for that Sunday.