alextes
alextes

Reputation: 2249

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 = ...

Upvotes: 9

Views: 14461

Answers (1)

alextes
alextes

Reputation: 2249

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

Upvotes: 18

Related Questions