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

1 Answer

0 votes
// Return all last Sundays of each month in a given year
function* lastSundaysOfYear(year: number): Generator<Date> {
    for (let month: number = 1; month <= 12; month++) {

        // Last day of the month
        let date: Date = new Date(year, month, 0); // day 0 of next month = last day of this month

        // Walk backward to Sunday
        while (date.getDay() !== 0) { // Sunday = 0
            const d: number = date.getDate();
            date = new Date(date.getFullYear(), date.getMonth(), d - 1);
        }

        yield new Date(date); // yield a copy
    }
}

function main(): void {
    const args: string[] = process.argv.slice(2);

    const year: number =
        args.length > 0
            ? parseInt(args[0], 10)
            : 2026;

    for (const date of lastSundaysOfYear(year)) {
        const mm: string = String(date.getMonth() + 1).padStart(2, "0");
        const dd: string = String(date.getDate()).padStart(2, "0");
        const yyyy: number = date.getFullYear();

        console.log(`${mm}/${dd}/${yyyy}`);
    }
}

main();



/*
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 9 hours ago by avibootz

Related questions

...