Search code examples
datetimerustrust-chrono

Chrono DateTime from u64 unix timestamp in Rust


How does one convert a u64 unix timestamp into a DateTime<Utc>?

let timestamp_u64 = 1657113606;
let date_time = ...

Solution

  • There are many options.

    Assuming we want a chrono::DateTime. The offset page suggests:

    Using the TimeZone methods on the UTC struct is the preferred way to construct DateTime instances.

    There is a TimeZone method timestamp_opt we can use.

    use chrono::{TimeZone, Utc};
        
    let timestamp_u64 = 1657113606;
    let date_time = Utc.timestamp_opt(timestamp_u64 as i64, 0).unwrap();
    

    playground