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

使用chrono crate:如何从DateTime/NaiveDateTime获取Duration?

解决chrono中时间差值计算的问题

嘿,我来帮你搞定这个chrono的时间计算问题!你遇到的Sub trait未实现的问题,核心原因是你用来相减的两个时间类型不匹配——NaiveDateTime是不带时区的时间,而Local::now()返回的是带本地时区的DateTime<Local>,这俩类型没法直接相减。下面分两种场景给你解决方案:

一、直接从时间对象计算Duration

你需要先把Local::now()转成和uEnd同类型的NaiveDateTime,用.naive_local()方法就行。这样两个同类型的时间对象就能直接相减,结果就是Duration了。示例代码如下:

use chrono::{Local, NaiveDateTime, Duration};

fn main() {
    // 示例i64时间戳
    let end64: i64 = 1735689600; 
    let u_end = NaiveDateTime::from_timestamp(end64, 0);
    
    // 获取当前时间并转为NaiveDateTime
    let current_naive = Local::now().naive_local();
    
    // 计算时间差,这里可以根据需求处理正负(比如取绝对值)
    let time_diff: Duration = if u_end > current_naive {
        u_end - current_naive
    } else {
        current_naive - u_end
    };

    println!("剩余时间:{}天{}小时", time_diff.num_days(), time_diff.num_hours() % 24);
}

二、从i64时间戳差值转换为Duration

如果已经算出了两个时间戳的i64差值(比如end64 - current_timestamp),直接用Duration的构造方法就能转换。因为timestamp()返回的是秒级的i64,所以用Duration::seconds()就可以:

use chrono::{Local, Duration};

fn main() {
    let end64: i64 = 1735689600;
    let current_timestamp = Local::now().timestamp();
    
    // 计算时间戳差值
    let timestamp_diff = end64 - current_timestamp;
    
    // 转换为Duration
    let duration = Duration::seconds(timestamp_diff);
    
    // 如果需要绝对值,用.abs()
    let abs_duration = duration.abs();
}

小提示

  • 如果你的时间戳是毫秒级的(比如返回的是i64毫秒数),记得用Duration::milliseconds()来构造,别搞错精度!
  • Duration提供了很多实用方法,比如num_days()、num_hours()、num_minutes(),可以直接把差值转成你需要的单位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:39:14