繁体   English   中英

如何从两个DateTime / NaiveDateTime获取持续时间?

[英]How do I get Duration from two DateTime / NaiveDateTime?

我正在使用chrono crate

我有日期i64 ,我可以得到NaiveDateTimeNaiveDateTime::from_timestamp

我有Local::now()当前时间,我可以通过.timestamp()获得i64

但我仍然无法理解如何获取my_time - current_time Duration my_time - current_time因为它告诉Sub如果我尝试它就不会实现

如果我在i64时间戳中获得差异,如何将其转换为Duration

例如,我想要类似的东西但是没有实现sub

let uEnd = NaiveDateTime::from_timestamp(end64, 0);
let dtEnd = uEnd.sub(Local::now());

两种日期时间类型不兼容,因为NaiveDateTime缺少时区。 在这种情况下,由于您是使用NaiveDateTime::from_timestamp获取的,因此可以NaiveDateTime::from_timestamp其转换为DateTime<Utc> ,然后使用signed_duration_since获取差异。

let now = Local::now();
let naive_dt = NaiveDate::from_ymd(2018, 3, 26).and_hms(10, 02, 0);
let other_dt = DateTime::<Utc>::from_utc(naive_dt, Utc);

let diff = now.signed_duration_since(other_dt);

操场


未来的版本chrono (0.4.1后)将支持减去作为替代呼叫.signed_duration_since ,只要两个操作数具有相同的时区类型。 PR#237因此,最终可以写下这个:

let diff = now.with_timezone(&Utc) - other_dt;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM