You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中正确实现日期减3年?解决闰年2月29日异常

解决Rust中日期减3年的闰年问题

原代码直接通过with_year将年份减3,当原日期为2月29日时,若目标年份不是闰年,unwrap()会触发panic——因为该年份不存在2月29日。以下是两种可行的解决方案:

方案一:准确处理闰年边界(推荐)

通过先尝试调整年份,失败时自动将日期回退到2月28日,确保结果有效:

use chrono::{DateTime, Utc};

pub fn today_three_years_earlier() -> DateTime<Utc> {
    let now = Utc::now();
    let now_date = now.date_utc();
    
    let three_years_ago_date = now_date.with_year(now_date.year() - 3)
        .unwrap_or_else(|| {
            // 原日期是2月29日,先退至2月28日再调整年份
            now_date.pred().with_year(now_date.year() - 3).unwrap()
        });
    
    three_years_ago_date.and_time(now.time())
}

该方案会保留原时间部分,同时正确处理闰年2月29日的特殊情况,返回合理的日期(比如2024年2月29日减3年,得到2021年2月28日)。

方案二:直接减去固定天数(忽略闰年)

如果不需要严格的年份对齐,仅需减去3×365天(共1095天),可以直接使用Duration实现:

use chrono::{DateTime, Duration, Utc};

pub fn today_three_years_earlier() -> DateTime<Utc> {
    Utc::now() - Duration::days(3 * 365)
}

这种方式实现简单,无需处理闰年逻辑,但结果会和实际年份差存在1天的误差(当期间包含闰年时)。

内容的提问来源于stack exchange,提问作者Fred Hors

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:22:27