Unix Timestamp in Rust
Rust's standard library provides SystemTime for basic timestamps. The chrono crate is the go-to for full datetime handling.
Get current timestamp (std only)
Rust
use std::time::{SystemTime, UNIX_EPOCH};
let epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
println!("{}", epoch.as_secs()); // seconds
println!("{}", epoch.as_millis()); // milliseconds
println!("{}", epoch.as_nanos()); // nanosecondsUsing chrono (recommended)
Rust — Cargo.toml
[dependencies]
chrono = "0.4"Rust — chrono
use chrono::{Utc, TimeZone, DateTime};
// Current timestamp
let now: DateTime<Utc> = Utc::now();
println!("{}", now.timestamp()); // seconds
println!("{}", now.timestamp_millis()); // milliseconds
println!("{}", now.to_rfc3339()); // ISO 8601
// Epoch to DateTime
let dt = Utc.timestamp_opt(1700000000, 0).unwrap();
println!("{}", dt); // 2023-11-14 22:13:20 UTC
println!("{}", dt.to_rfc3339()); // "2023-11-14T22:13:20+00:00"
println!("{}", dt.format("%Y-%m-%d %H:%M:%S"));
// DateTime to epoch
let epoch: i64 = dt.timestamp();Timezone conversion with chrono-tz
Rust
// Cargo.toml: chrono-tz = "0.8"
use chrono::Utc;
use chrono_tz::Asia::Kolkata;
let utc = Utc.timestamp_opt(1700000000, 0).unwrap();
let ist = utc.with_timezone(&Kolkata);
println!("{}", ist); // 2023-11-15 03:43:20 ISTTime arithmetic
Rust
use chrono::{Utc, Duration};
let now = Utc::now();
let future = now + Duration::days(1);
let past = now - Duration::hours(6);
// Check expiry
let expiry = Utc.timestamp_opt(1700000000, 0).unwrap();
if Utc::now() > expiry {
println!("expired");
}→ Use the live epoch converter to convert any Rust timestamp instantly.