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

1 Answer

0 votes
// Zeller's Congruence implementation
// Returns the day of the week for a given date.
fn day_of_week(d: i32, m: i32, y: i32) -> &'static str {

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

    let mut m = m;
    let mut y = y;

    // 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
    }

    let k = y % 100;   // Year of the century (last two digits)
    let j = y / 100;   // Zero-based century (e.g., 2024 → 20)

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

    let term1 = d;                     // day of month
    let term2 = (13 * (m + 1)) / 5;    // month adjustment
    let term3 = k;                     // year of century
    let term4 = k / 4;                 // leap years in century
    let term5 = j / 4;                 // leap centuries
    let term6 = 5 * j;                 // century correction

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

    // Return the corresponding weekday name
    names[h as usize]
}

fn main() {
    let d = 30;
    let m = 5;
    let y = 2024;

    println!("{}", day_of_week(d, m, y));
}



/*
run:

Thursday

*/

 



answered 6 hours ago by avibootz
...