Unix Timestamps in Rust
Rust's standard library provides SystemTime and UNIX_EPOCH for basic timestamp work. For formatting and timezone support, the chrono crate is the standard choice.
Get the current Unix timestamp (std only)
No external crate needed for basic epoch seconds using std::time.
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
let now = SystemTime::now();
let since_epoch = now.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
// Seconds
println!("{}", since_epoch.as_secs());
// Milliseconds
println!("{}", since_epoch.as_millis());
}
AdSense — In-Article Banner
Convert a timestamp to a readable date with chrono
Add chrono = "0.4" to your Cargo.toml, then use DateTime::from_timestamp().
use chrono::{DateTime, Utc, TimeZone};
fn main() {
let ts: i64 = 1700000000;
// Convert to UTC DateTime
let dt: DateTime<Utc> = Utc.timestamp_opt(ts, 0).unwrap();
println!("{}", dt.to_rfc3339());
// Output: 2023-11-14T22:13:20+00:00
}
Convert a date back to a Unix timestamp
use chrono::{TimeZone, Utc};
fn main() {
let dt = Utc.with_ymd_and_hms(2026, 1, 15, 12, 0, 0).unwrap();
// Seconds since epoch
println!("{}", dt.timestamp());
// Milliseconds since epoch
println!("{}", dt.timestamp_millis());
}
AdSense — In-Article Banner