【问题标题】:How do I add a month to a Chrono NaiveDate?如何为 Chrono NaiveDate 添加一个月?
【发布时间】:2021-01-12 19:16:22
【问题描述】:

我正在尝试创建一个日期选择器,我需要在月份之间导航

let current = NaiveDate::parse_from_str("2020-10-15", "%Y-%m-%d").unwrap();

如何生成日期2020-11-15

【问题讨论】:

    标签: rust rust-chrono


    【解决方案1】:

    这是我的解决方案:

    use chrono::{ NaiveDate, Duration, Datelike};
    
    fn get_days_from_month(year: i32, month: u32) -> u32 {
        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() as u32
    }
    
    fn add_months(date: NaiveDate, num_months: u32) -> NaiveDate {
        let mut month = date.month() + num_months;
        let year = date.year() + (month / 12) as i32;
        month = month % 12;
        let mut day = date.day();
        let max_days = get_days_from_month(year, month);
        day = if day > max_days { max_days } else { day };
        NaiveDate::from_ymd(year, month, day)
    }
    
    fn main() {
        let date = NaiveDate::parse_from_str("2020-10-31", "%Y-%m-%d").unwrap();
        let new_date = add_months(date, 4);
        println!("{:?}", new_date);
    }
    

    【讨论】:

      【解决方案2】:

      您实际上是在要求两种不同的东西。转到下个月与在日期中添加月份不同,因为对于后者,您还必须考虑当月日期的有效性。例如,如果您在 1 月 29 日加上一个月,您通常会在 3 月而不是 2 月结束,因为通常没有 2 月 29 日,当然闰年除外。

      仅处理年和月要简单得多,因为一年中的月数与每年相同。因此,要回答如何在日期选择器中在月份之间导航的基本问题,请参考:

      fn next_month(year: i32, month: u32) -> (i32, u32) {
        assert!(month >= 1 && month <= 12);
      
        if month == 12 {
          (year + 1, 1)
        } else {
          (year, month + 1)
        }
      }
      
      fn prev_month(year: i32, month: u32) -> (i32, u32) {
        assert!(month >= 1 && month <= 12);
      
        if month == 1 {
          (year - 1, 12)
        } else {
          (year, month - 1)
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-23
        • 1970-01-01
        • 2021-03-29
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多