如何将自纪元以来的Unix时间/时间转换为标准日期和时间?

时间:2017-03-03 06:29:00

标签: time rust rust-chrono

我正在使用计时箱;经过一番挖掘后,我发现DateTime类型的函数timestamp()可以生成i64类型的纪元时间。但是,我无法找到如何将其转换回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?
}

2 个答案:

答案 0 :(得分:6)

您首先需要创建NaiveDateTime,然后再使用它来再次创建DateTime

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);
}

Playground

答案 1 :(得分:0)

您可以使用parse_duration条板箱:https://docs.rs/parse_duration/2.1.0/parse_duration/

extern crate parse_duration;
use parse_duration::parse;
use std::time::Duration;

fn main() {
    // 1587971749 seconds since UNIX_EPOCH
    assert_eq!(parse("1587971749"), Ok(Duration::new(1587971749, 0)));

    // One hour less than a day
    assert_eq!(parse("1 day -1 hour"), Ok(Duration::new(82_800, 0)));

    // Using exponents
    assert_eq!(
        parse("1.26e-1 days"),
        Ok(Duration::new(10_886, 400_000_000))
    );

    // Extra things will be ignored
    assert_eq!(
        parse("Duration: 1 hour, 15 minutes and 29 seconds"),
        Ok(Duration::new(4529, 0))
    );
}