如何使用时间 rs 板条箱将秒数添加到当前日期



我想在当前时间上增加100秒。我正在使用这个库

use time::PrimitiveDateTime as DateTime;
pub fn after(start: DateTime) -> DateTime {
start + 100 seconds // something like this to the start DateTime
}

您可以创建一个time::Duration,可以将其添加到PrimitiveDateTime中。当前时间需要从OffsetDateTime中获取,但可以很容易地用于构建您的start

use time::Duration;
use time::OffsetDateTime;
use time::PrimitiveDateTime as DateTime;
pub fn after(start: DateTime) -> DateTime {
start + Duration::seconds(100)
}
fn main() {
let now = OffsetDateTime::now_utc();
let start = DateTime::new(now.date(), now.time());
println!("{:?}", now);
println!("{:?}", start);
println!("{:?}", after(start));
}

我不知道您是否有理由使用PrimitiveDateTime,但它不包含任何时区信息,所以我建议替换它们,因为OffsetDateTime仍然包含原语,并且需要获取当前时间:

use time::Duration;
use time::OffsetDateTime as DateTime;
pub fn after(start: DateTime) -> DateTime {
start + Duration::seconds(100)
}
fn main() {
let now = DateTime::now_utc();
println!("{:?}", now);
println!("{:?}", after(now));
}