How to get the month name from a date in Rust

2 Answers

0 votes
use chrono::NaiveDate;
use chrono::Datelike;
 
fn main() {
    let date = NaiveDate::from_ymd_opt(2025, 1, 7).expect("Invalid date");
 
    // Get the month as a number
    let month = date.month();
 
    // Convert the month number to a month name
    let month_name = match month {
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        12 => "December",
        _ => "Invalid month",
    };
 
    println!("{}", month_name);
}
 
 
  
/*
run:
  
January
 
*/

 



answered Jan 7, 2025 by avibootz
edited Jan 7, 2025 by avibootz
0 votes
use chrono::NaiveDate;

fn main() {
    let date = NaiveDate::from_ymd_opt(2025, 1, 7).expect("Invalid date");
    
    let month_name = date.format("%B").to_string();
    
    println!("{}", month_name);
}


 
/*
run:
 
January

*/

 



answered Jan 7, 2025 by avibootz
...