我正在使用chrono条板箱,并希望在两个Duration
之间计算DateTime
。
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();
答案 0 :(得分:4)
DateTime
实现了Sub<DateTime>
,因此您可以从第一个日期中减去最近的日期:
let duration = end_of_period - start_of_period;
println!("num days = {}", duration.num_days());
答案 1 :(得分:4)
看到Utc的文档:https://docs.rs/chrono/0.4.11/chrono/offset/struct.Utc.html
通过调用方法.now
(或.today
),您将返回一个实现Sub<Date<Tz>> for Date<Tz>
的结构,从源头您可以看到它正在返回OldDuration
,只是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();