How to find the dates of the last Sunday of each month of a given year in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
 
public static class LastSundays
{
    // Return all last Sundays of each month in a given year
    public static IEnumerable<DateTime> LastSundaysOfYear(int year)
    {
        for (int month = 1; month <= 12; month++) {
            // Last day of the month
            var date = new DateTime(year, month, 1)
                .AddMonths(1)
                .AddDays(-1);
 
            // Walk backward to Sunday
            while (date.DayOfWeek != DayOfWeek.Sunday) {
                date = date.AddDays(-1);
            }
 
            yield return date;
        }
    }
     
    public static void Main(string[] args)
    {
        int year = (args.Length > 0)
            ? int.Parse(args[0])
            : 2026;
            
        foreach (var date in LastSundays.LastSundaysOfYear(year)) {
            Console.WriteLine(date.ToString("MM/dd/yyyy"));
        }
    }
}
 
 
/*
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

...