Search code examples
timerustrust-chrono

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


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

Solution

  • 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