Search code examples
rust

How to get the number of days in a month in Rust?


Is there a idiomatic Rust way to get the number of days in a given month? I've looked at chrono but I haven't found anything in the docs for this.

I'm looking for something that can manage leap years similar to calendar.monthrange in Python or DateTime.DaysInMonth in C# .


Solution

  • You can use NaiveDate::signed_duration_since from the chrono crate:

    use chrono::NaiveDate;
    
    fn main() {
        let year = 2018;
        for (m, d) in (1..=12).map(|m| {
            (
                m,
                if m == 12 {
                    NaiveDate::from_ymd(year + 1, 1, 1)
                } else {
                    NaiveDate::from_ymd(year, m + 1, 1)
                }.signed_duration_since(NaiveDate::from_ymd(year, m, 1))
                .num_days(),
            )
        }) {
            println!("days {} in month {}", d, m);
        }
    }