How to convert Unix time / time since the epoch to standard date and time?

坚强是说给别人听的谎言 提交于 2019-12-01 15:29:39

问题


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?
}

回答1:


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

Playground



来源:https://stackoverflow.com/questions/42572107/how-to-convert-unix-time-time-since-the-epoch-to-standard-date-and-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!