How to calculate the number of weekdays between two dates in VB.NET

1 Answer

0 votes
Imports System

Public Class WeekdayCalculatorBetweenTwoDates
    Public Shared Sub Main()
        Console.WriteLine(countWeekDays(New DateTime(2025, 1, 1), New DateTime(2025, 1, 7)))
        Console.WriteLine(countWeekDays(New DateTime(2025, 2, 1), New DateTime(2025, 2, 10)))
        Console.WriteLine(countWeekDays(New DateTime(2024, 1, 1), New DateTime(2024, 12, 31)))
        Console.WriteLine(countWeekDays(New DateTime(2025, 1, 1), New DateTime(2025, 12, 31)))
    End Sub

    Public Shared Function countWeekDays(ByVal d1 As DateTime, ByVal d2 As DateTime) As Integer
        Dim ndays As Integer = 1 + Convert.ToInt32((d2 - d1).TotalDays)
        Dim nsaturdays As Integer = (ndays + Convert.ToInt32(d1.DayOfWeek)) / 7
		
        Return ndays - 2 * nsaturdays - (If(d1.DayOfWeek = DayOfWeek.Sunday, 1, 0)) + (If(d2.DayOfWeek = DayOfWeek.Saturday, 1, 0))
    End Function
End Class



' run:
'
' 5
' 6
' 262
' 259
'

 



answered Feb 18, 2025 by avibootz
...