How to get system time from unix epoch

I've unix epoch nanoseconds. How to convert into time.

Hi,

I found this snippet it seem to works:

extern crate chrono;
use chrono::prelude::DateTime;
use chrono::Utc;
use std::time::{SystemTime, UNIX_EPOCH, Duration};


fn main(){
    // Creates a new SystemTime from the specified number of whole seconds
    let d = UNIX_EPOCH + Duration::from_secs(1524885322);
    // Create DateTime from SystemTime
    let datetime = DateTime::<Utc>::from(d);
    // Formats the combined date and time with the specified format string.
    let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S.%f").to_string();
    println!{"{}",timestamp_str};
}

You just need to change Duration::from_secs() to Duration::from_nanos().

Cheers

1 Like

When you copy a bit of code from someone else, please link back to the original source, or at least mention the original author’s name. If someone is providing something gratis, the least we can do is recognize the contribution.

3 Likes

Worth noting it's also generally a requirement to provide attribution under whatever license that snippet was provided.

1 Like