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

1 Answer

0 votes
Imports System
Imports System.Globalization
Imports System.Collections.Generic

Public Module LastFridaysOfYearProgram

    ' Return all last Fridays of each month in a given year
    Private Iterator Function LastFridaysOfYear(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 Friday
            While dateValue.DayOfWeek <> DayOfWeek.Friday
                dateValue = dateValue.AddDays(-1)
            End While

            Yield dateValue
        Next
    End Function

    Public Sub Main(args As String())

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

        For Each dateValue As DateTime In LastFridaysOfYear(year)
            Console.WriteLine(dateValue.ToString("d", CultureInfo.InvariantCulture))
        Next

    End Sub

End Module

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

 



answered May 23 by avibootz

Related questions

...