How to find the day of the week on any given date in TypeScript

1 Answer

0 votes
// Zeller's Congruence implementation
// Returns the day of the week for a given date.
function dayOfWeek(d: number, m: number, y: number): string {

    // Zeller's output mapping:
    // 0 = Saturday, 1 = Sunday, 2 = Monday, ... 6 = Friday
    const names: string[] = [
        "Saturday", "Sunday", "Monday", "Tuesday",
        "Wednesday", "Thursday", "Friday"
    ];

    // In Zeller's formula, January and February are counted
    // as months 13 and 14 of the previous year.
    if (m < 3) {
        m += 12;   // Convert Jan → 13, Feb → 14
        y -= 1;    // Move to previous year
    }

    const K: number = y % 100;          // Year of the century (last two digits)
    const J: number = Math.floor(y / 100);  // Zero-based century (e.g., 2024 → 20)

    // Zeller's formula (clearer step-by-step version):

    const term1: number = d;                        // day of month
    const term2: number = Math.floor(13 * (m + 1) / 5); // month adjustment
    const term3: number = K;                        // year of century
    const term4: number = Math.floor(K / 4);        // leap years in century
    const term5: number = Math.floor(J / 4);        // leap centuries
    const term6: number = 5 * J;                    // century correction

    // Combine all terms and take modulo 7
    const h: number = (term1 + term2 + term3 + term4 + term5 + term6) % 7;

    // Return the corresponding weekday name
    return names[h];
}

const d = 30, m = 5, y = 2024;

console.log(dayOfWeek(d, m, y));



/*
run:

Thursday

*/

 



answered 6 hours ago by avibootz
...