如何计算两个chrono::DateTime之间的持续时间?

How to compute the duration between two chrono::DateTime?

我正在使用 chrono 箱子并想计算两个 DateTime 之间的 Duration

use chrono::Utc;
use chrono::offset::TimeZone;

let start_of_period = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let end_of_period = Utc.ymd(2021, 1, 1).and_hms(0, 0, 0);

// What should I enter here?
//
// The goal is to find a duration so that
// start_of_period + duration == end_of_period
// I expect duration to be of type std::time
let duration = ... 

let nb_of_days = duration.num_days();

DateTime 实现了 Sub<DateTime>,因此您只需从第一个日期中减去最近的日期即可:

let duration = end_of_period - start_of_period;
println!("num days = {}", duration.num_days());

查看 Utc 文档:https://docs.rs/chrono/0.4.11/chrono/offset/struct.Utc.html

通过调用方法 .now(或 .today),您将返回一个实现 Sub<Date<Tz>> for Date<Tz>, from source you can see it is returning an OldDuration, which is just a type alias around Duration.

的结构

最后,您可以将 Duration 与其他实现 Add 的类型一起使用,例如 DateTime.

所以代码应该是这样的:

let start_of_period = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let end_of_period = Utc.ymd(2021, 1, 1).and_hms(0, 0, 0);

let duration = end_of_period.now() - start_of_period.now();