首页 > 解决方案 > 如何在 Rust 中获取一个月的天数?

问题描述

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

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

标签: rust

解决方案


您可以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);
    }
}

推荐阅读