如何在 Rust 中获取当前日期和时间的时间戳

Sam*_*sel 18 datetime rust

我只想检索当前的时间和日期并将其存储在一个变量中。为此,我尝试使用 chrono::DateTime。

在文档中,我发现了这一点:

use chrono::{DateTime, TimeZone, NaiveDateTime, Utc};

let dt = DateTime::<Utc>::from_utc(NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11), Utc);    
Run Code Online (Sandbox Code Playgroud)

这让我可以存储特定的日期和时间,但我无法弄清楚如何检索实际的当前日期和时间并将其放入我的日期时间变量中。

edw*_*rdw 21

使用锈,使用它now

use chrono;

fn main() {
    println!("{:?}", chrono::offset::Local::now());
    println!("{:?}", chrono::offset::Utc::now());
}
Run Code Online (Sandbox Code Playgroud)

  • @0x12 除了它仍然有效?`chrono` 的最新版本(0.4.23)确实表示 `Utc::now` 现在支持 crate 功能,但代码仍然按原样编译。 (3认同)

I.A*_*Guy 16

回答标题中的问题如何获取当前时间戳:

use chrono::Utc;

let dt = Utc::now();
let timestamp: i64 = dt.timestamp();

println!("Current timestamp is {}", timestamp);
Run Code Online (Sandbox Code Playgroud)