【问题标题】:How to compute the duration between two chrono::DateTime?如何计算两个 chrono::DateTime 之间的持续时间?
【发布时间】:2020-07-17 08:04:14
【问题描述】:

我正在使用 chrono 板条箱并希望计算两个 DateTimes 之间的 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();

【问题讨论】:

    标签: rust rust-chrono


    【解决方案1】:

    DateTime 实现了Sub<DateTime>,所以你可以从第一个日期中减去最近的日期:

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

    【讨论】:

      【解决方案2】:

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

      通过调用.now(或.today)方法,您将返回一个实现Sub<Date<Tz>> for Date<Tz>的结构,从源代码中您可以看到它返回一个OldDuration,它只是@987654323 周围的一个类型别名@。

      最后,您可以将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();
      

      【讨论】:

        猜你喜欢
        • 2020-06-28
        • 1970-01-01
        • 2021-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 2017-11-15
        相关资源
        最近更新 更多