如何在 Rust 中获得一个月的天数?

lud*_*fet 5 rust

是否有惯用的 Rust 方法来获取给定月份的天数?我看过 chrono ,但在文档中没有找到任何关于此的内容。

我正在寻找可以管理类似于calendar.monthrangePython 或DateTime.DaysInMonthC# 中的闰年的东西。

fgh*_*ghj 6

您可以NaiveDate::signed_duration_sincechrono板条箱中使用:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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()
}
Run Code Online (Sandbox Code Playgroud)