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

1 Answer

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

        // Last day of the month
        // In JS/TS: new Date(year, month, 0) = last day of previous month
        let date: Date = new Date(year, month, 0);

        // Walk backward to Friday
        while (date.getDay() !== 5) { // 5 = Friday
            date.setDate(date.getDate() - 1);
        }

        yield date;
    }
}

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

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

    const formatter: Intl.DateTimeFormat =
        new Intl.DateTimeFormat("en-US");

    for (const date of lastFridaysOfYear(year)) {
        console.log(formatter.format(date));
    }
}

main();



/*
run:

1/30/2026
2/27/2026
3/27/2026
4/24/2026
5/29/2026
6/26/2026
7/31/2026
8/28/2026
9/25/2026
10/30/2026
11/27/2026
12/25/2026

*/

 



answered 9 hours ago by avibootz

Related questions

...