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

1 Answer

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

        // Last day of the month
        let 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
            date.setDate(date.getDate() - 1);
        }

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

function main() {
    const args = process.argv.slice(2);

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

    for (const date of lastSundaysOfYear(year)) {
        const mm = String(date.getMonth() + 1).padStart(2, "0");
        const dd = String(date.getDate()).padStart(2, "0");
        const yyyy = 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 10 hours ago by avibootz

Related questions

...