Unix timestamps in Rust
Get the current epoch time and convert between timestamps and dates in Rust. Every snippet below is copy-ready.
// note
std gives seconds; use chrono or time for parsing and formatting.
now.rs · current timestamp
use std::time::{SystemTime, UNIX_EPOCH};
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)?
.as_secs();
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)?
.as_millis();
timestamp → date
use chrono::{DateTime, Utc};
let ts: i64 = 1_700_000_000;
let dt = DateTime::<Utc>::from_timestamp(ts, 0)
.expect("valid timestamp");
println!("{}", dt.to_rfc3339());
date → timestamp
use chrono::{TimeZone, Utc};
let ts = Utc.with_ymd_and_hms(2023, 11, 14, 22, 13, 20)
.unwrap()
.timestamp();
// current epoch
— seconds since 1970-01-01T00:00:00Z.
Watch out for these
- Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
- Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
- Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.
Reference: https://docs.rs/chrono/latest/chrono/