Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 289
Victor Basso Avatar asked May 01 '18 21:05

Victor Basso


2 Answers

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)
like image 122
mcarton Avatar answered Sep 28 '22 05:09

mcarton


This is almost answered with a quote from the 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.

So, adding a duration to a Chrono date-time has to be done with this OldDuration, which is actually exported from the root of the crate with the name Duration:

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

Then, adding a duration can be done by either creating an OldDuration directly:

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

Or by converting a standard duration.

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

This experience might be improved before chrono reaches 1.0.0.

like image 27
E_net4 stands with Ukraine Avatar answered Sep 28 '22 05:09

E_net4 stands with Ukraine