How to find the day of the week on any given date in VB.NET

1 Answer

0 votes
Imports System

Public Module MainModule

    ' Zeller's Congruence implementation
    ' Returns the day of the week for a given date.
    Public Function dayOfWeek(d As Integer, m As Integer, y As Integer) As String

        ' Zeller's output mapping:
        ' 0 = Saturday, 1 = Sunday, 2 = Monday, ... 6 = Friday
        Dim names() As String = {
            "Saturday", "Sunday", "Monday", "Tuesday",
            "Wednesday", "Thursday", "Friday"
        }

        ' In Zeller's formula, January and February are counted
        ' as months 13 and 14 of the previous year.
        If m < 3 Then
            m += 12   ' Convert Jan → 13, Feb → 14
            y -= 1    ' Move to previous year
        End If

        Dim K As Integer = y Mod 100   ' Year of the century (last two digits)
        Dim J As Integer = y \ 100     ' Zero-based century (e.g., 2024 → 20)

        ' Zeller's formula (clearer step-by-step version):

        Dim term1 As Integer = d                     ' day of month
        Dim term2 As Integer = (13 * (m + 1)) \ 5    ' month adjustment
        Dim term3 As Integer = K                     ' year of century
        Dim term4 As Integer = K \ 4                 ' leap years in century
        Dim term5 As Integer = J \ 4                 ' leap centuries
        Dim term6 As Integer = 5 * J                 ' century correction

        ' Combine all terms and take modulo 7
        Dim h As Integer = (term1 + term2 + term3 + term4 + term5 + term6) Mod 7

        ' Return the corresponding weekday name
        Return names(h)
    End Function

    Sub Main()
        Dim d As Integer = 30
        Dim m As Integer = 5
        Dim y As Integer = 2024

        Console.WriteLine(dayOfWeek(d, m, y))
    End Sub

End Module


'
' run:
'
' Thursday
'

 



answered 8 hours ago by avibootz
...