如何将自纪元以来的 Unix 时间/时间转换为标准日期和时间?
问题描述:
我正在使用chrono crate;经过一番挖掘,我发现 DateTime
类型有一个函数 timestamp()
,它可以生成 i64
类型的纪元时间.但是,我不知道如何将其转换回 DateTime
.
I'm using the chrono crate; after some digging I discovered the DateTime
type has a function timestamp()
which could generate epoch time of type i64
. However, I couldn't find out how to convert it back to DateTime
.
extern crate chrono;
use chrono::*;
fn main() {
let date = chrono::UTC.ymd(2020, 1, 1).and_hms(0, 0, 0);
println!("{}", start_date.timestamp());
// ...how to convert it back?
}
答
你首先需要创建一个NaiveDateTime
,然后再用它创建一个DateTime
:>
You first need to create a NaiveDateTime
and then use it to create a DateTime
again:
extern crate chrono;
use chrono::prelude::*;
fn main() {
let datetime = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let timestamp = datetime.timestamp();
let naive_datetime = NaiveDateTime::from_timestamp(timestamp, 0);
let datetime_again: DateTime<Utc> = DateTime::from_utc(naive_datetime, Utc);
println!("{}", datetime_again);
}