How to print a calendar for a specific month and year in Rust

1 Answer

0 votes
use chrono::{Datelike, NaiveDate, Days};

fn print_month(year: i32, month: u32) {
    let first = NaiveDate::from_ymd_opt(year, month, 1).unwrap();

    let next_month = if month == 12 {
        NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap()
    } else {
        NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap()
    };

    let last_day = next_month.checked_sub_days(Days::new(1)).unwrap();
    let days_in_month = last_day.day();

    let month_name = first.format("%B").to_string();

    println!("     {} {}", month_name, year);
    println!("Su Mo Tu We Th Fr Sa");

    let offset = first.weekday().num_days_from_sunday();

    for _ in 0..offset {
        print!("   ");
    }

    for day in 1..=days_in_month {
        print!("{:2} ", day);
        if (offset + day) % 7 == 0 {
            println!();
        }
    }

    println!();
}

fn main() {
    print_month(2026, 1);
}



/*
run:

     January 2026
Su Mo Tu We Th Fr Sa
             1  2  3 
 4  5  6  7  8  9 10 
11 12 13 14 15 16 17 
18 19 20 21 22 23 24 
25 26 27 28 29 30 31 

*/

 



answered Jan 18 by avibootz

Related questions

...