How to find the dates of the last Sunday of each month of a given year in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Module LastSundays

    ' Return all last Sundays of each month in a given year
    Public Iterator Function LastSundaysOfYear(year As Integer) As IEnumerable(Of DateTime)
        For month As Integer = 1 To 12

            ' Last day of the month
            Dim dateValue As DateTime =
                New DateTime(year, month, 1).
                    AddMonths(1).
                    AddDays(-1)

            ' Walk backward to Sunday
            While dateValue.DayOfWeek <> DayOfWeek.Sunday
                dateValue = dateValue.AddDays(-1)
            End While

            Yield dateValue
        Next
    End Function

    Sub Main(args As String())
     	Dim year As Integer =
            If(args.Length > 0,
               Integer.Parse(args(0)),
               2026)    

		For Each dateValue As DateTime In LastSundaysOfYear(year)
            Console.WriteLine(dateValue.ToString("MM/dd/yyyy"))
        Next
    End Sub

End Module



' run:
'
' 01/25/2026
' 02/22/2026
' 03/29/2026
' 04/26/2026
' 05/31/2026
' 06/28/2026
' 07/26/2026
' 08/30/2026
' 09/27/2026
' 10/25/2026
' 11/29/2026
' 12/27/2026
'


 



answered May 23 by avibootz
edited May 24 by avibootz

Related questions

...