How to get the number of the day from the beginning of the year to a given date in Rust

1 Answer

0 votes
fn is_leap_year(year: u32) -> bool {
    (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))
}

fn get_day_of_year(year: u32, month: usize, day: u32) -> u32 {
    // cumulative days at the end of each month (non-leap year)
    let days: [u32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];

    if is_leap_year(year) && month > 2 {
        days[month - 1] + day + 1
    } else {
        days[month - 1] + day
    }
}

fn main() {
    let day_of_year = get_day_of_year(2023, 5, 15);
    
    println!("{}", day_of_year);
}



/*
run:

135

*/

 



answered Dec 13, 2025 by avibootz

Related questions

...