Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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# .

like image 275
ludofet Avatar asked Dec 08 '18 21:12

ludofet


2 Answers

pub fn get_days_from_month(year: i32, month: u32) -> i64 {
    NaiveDate::from_ymd(
        match month {
            12 => year + 1,
            _ => year,
        },
        match month {
            12 => 1,
            _ => month + 1,
        },
        1,
    )
    .signed_duration_since(NaiveDate::from_ymd(year, month, 1))
    .num_days()
}
like image 78
Boussif Asma Avatar answered Oct 21 '22 19:10

Boussif Asma


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);
    }
}
like image 34
fghj Avatar answered Oct 21 '22 17:10

fghj