Rust trait`std::ops::Add<;标准::时间::持续时间>;`未为'chrono::DateTime'实现;时钟:Utc>` extern板条箱计时; 使用chrono::{DateTime,Utc}; 使用std::time::Duration; pub fn after(开始:DateTime)->DateTime{ 开始+持续时间::从秒开始(1) }
在以下情况下失败:Rust trait`std::ops::Add<;标准::时间::持续时间>;`未为'chrono::DateTime'实现;时钟:Utc>` extern板条箱计时; 使用chrono::{DateTime,Utc}; 使用std::time::Duration; pub fn after(开始:DateTime)->DateTime{ 开始+持续时间::从秒开始(1) },rust,rust-chrono,Rust,Rust Chrono,在以下情况下失败: error[E0277]:无法将'std::time::Duration'添加到'chrono::DateTime'` -->src/lib.rs:7:11 | 7 |开始+持续时间::从秒开始(1 | 000 | 000 |) |^chrono::DateTime+std::time::Duration没有实现` | =help:trait`std::ops::Add`未为`chrono::DateTime'实现` 我找不到要导入的Add的实现使用chrono::*不会有
error[E0277]:无法将'std::time::Duration'添加到'chrono::DateTime'`
-->src/lib.rs:7:11
|
7 |开始+持续时间::从秒开始(1 | 000 | 000 |)
|^chrono::DateTime+std::time::Duration没有实现`
|
=help:trait`std::ops::Add`未为`chrono::DateTime'实现`
我找不到要导入的Add
的实现<代码>使用chrono::*不会有帮助
我看到datetime.rs
有一个impl forAdd
,但是oldtime
是私有的,所以我不知道如何创建oldtime::Duration
如何获取所需的Add
impl?如何将std::time::Duration
转换为chrono::oldtime::Duration
?是否有可以导入以隐式转换的内容
我使用的是
rustc 1.25.0(84203cac6 2018-03-25)
这几乎可以用chrono
中的一句话来回答:
Chrono当前使用时间框中的time::Duration
类型来表示时间跨度的大小。由于其与较新的标准持续时间类型具有相同的名称,因此参考将此类型称为OldDuration
。[……]
Chrono本机还不支持标准的Duration
类型,但将来将支持该类型。同时,您可以使用Duration::from_std
和Duration::to_std
方法在两种类型之间进行转换
因此,向计时日期时间添加持续时间必须使用此OldDuration
,它实际上具有名称duration
:
extern crate chrono;
use chrono::{DateTime, Utc};
use std::time::Duration;
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
start + Duration::from_secs(1)
}
然后,可以通过直接创建OldDuration
来添加持续时间:
use chrono::{DateTime, Utc, Duration as OldDuration};
pub fn after(开始:DateTime)->DateTime{
开始+旧持续时间::秒(1)
}
或者通过转换标准持续时间
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
start + OldDuration::seconds(1)
}
pub fn after(开始:DateTime)->DateTime{
start+OldDuration::from_std(Duration::from_secs(1)).unwrap()
}
在
chrono
达到1.0.0之前,此体验可能会得到改善。有转换函数和std::time::Duration
,因此您可以执行以下操作:
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
start + OldDuration::from_std(Duration::from_secs(1)).unwrap()
}
但是如果你能坚持使用chrono
,那就坚持使用chrono
:
start + ::chrono::Duration::from_std(Duration::from_secs(1)).expect("1s can't overflow")
该死,你用一个更好的答案赢了我10秒:)@mcarton我通常不是西部最快的枪。但是当我在的时候,我仍然坚持我的标准最好拿上我的牛仔帽,你说得对!我不知何故假设没有
chrono::Duration
。顺便说一句,如果“chrono当前使用time::Duration
”(@E_net4的答案),我不明白它如何在chrono
命名空间中结束。我甚至可以在std::time
和chrono::oldtime
的源代码中找到定义的持续时间(IDE将我带到那里)。但我无法在chrono
中直接看到它。关于rust模块的工作原理,我缺少了一些东西,我会再次犯这个错误。@Vituel板条箱可以(而且经常)用pub use重新导出东西。是Duration
在chrono
的根中结束的方式。我已相应地更新了我的答案。
use chrono::{DateTime, Utc, Duration};
start + Duration::seconds(1)