特性 `std::ops::Add<std::time::Duration>` 没有为 `chrono::DateTime<chrono::Utc>` 实现

The trait `std::ops::Add<std::time::Duration>` is not implemented for `chrono::DateTime<chrono::Utc>`

extern crate chrono;
use chrono::{DateTime, Utc};
use std::time::Duration;

pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
    start + Duration::from_secs(1)
}

失败:

error[E0277]: cannot add `std::time::Duration` to `chrono::DateTime<chrono::Utc>`
 --> src/lib.rs:7:11
  |
7 |     start + Duration::from_secs(1_000_000_000)
  |           ^ no implementation for `chrono::DateTime<chrono::Utc> + std::time::Duration`
  |
  = help: the trait `std::ops::Add<std::time::Duration>` is not implemented for `chrono::DateTime<chrono::Utc>`

我找不到要导入的 Add 的实现。 use chrono::* 无济于事。

我看到 datetime.rs 有一个对 Add<chrono::oldtime::Duration> 的实现,但是 oldtime 是私有的,所以我不知道如何创建 oldtime::Duration.

如何获得我需要的 Add impl?如何将 std::time::Duration 转换为 chrono::oldtime::Duration?有什么我可以导入以隐式转换的东西吗?

我正在使用 rustc 1.25.0 (84203cac6 2018-03-25)

这几乎可以用 chrono documentation:

中的一句话来回答

Chrono currently uses the time::Duration type from the time crate to represent the magnitude of a time span. Since this has the same name to the newer, standard type for duration, the reference will refer this type as OldDuration. [...]

Chrono does not yet natively support the standard Duration type, but it will be supported in the future. Meanwhile you can convert between two types with Duration::from_std and Duration::to_std methods.

因此,必须使用此 OldDuration 向 Chrono 日期时间添加持续时间,这实际上是 exported from the root of the crate,名称为 Duration:

use chrono::{DateTime, Utc, Duration as OldDuration};

然后,可以通过直接创建 OldDuration 来添加持续时间:

pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
    start + OldDuration::seconds(1)
}

或者通过转换标准持续时间。

pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
    start + OldDuration::from_std(Duration::from_secs(1)).unwrap()
}

此体验可能会在 chrono 达到 1.0.0 之前得到改进。

有函数可以转换 from and to std::time::Duration 所以你可以这样做:

start + ::chrono::Duration::from_std(Duration::from_secs(1)).expect("1s can't overflow")

但是如果你能坚持chrono,就坚持chrono:

use chrono::{DateTime, Utc, Duration};
start + Duration::seconds(1)