Search code examples
rustrust-chrono

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)
}

fails with:

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>`

I couldn't find an implementation of Add to import. use chrono::* won't help.

I see that datetime.rs has an impl for Add<chrono::oldtime::Duration>, but oldtime is private so I don't know how to create an oldtime::Duration.

How do I get the Add impl I need? How do I convert std::time::Duration to chrono::oldtime::Duration? Is there something I can import to convert implicitly?

I'm using rustc 1.25.0 (84203cac6 2018-03-25)


Solution

  • There are functions to convert from and to std::time::Duration so you could just do:

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

    But if you can just stick with chrono, just stick with chrono:

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