Unix Timestamp in Rust

Rust's standard library provides SystemTime for Unix timestamps. For richer date handling, the chrono crate is the community standard.

Ad

Code Examples

Current timestamp (seconds) — std only

use std::time::SystemTime;

fn main() {
    let secs = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    println!("{secs}");
}

No external crates needed. duration_since returns a Duration — .as_secs() gives u64 seconds since epoch.

Current timestamp (milliseconds) — std only

use std::time::SystemTime;

let ms = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .unwrap()
    .as_millis(); // u128

as_millis() returns u128 — note the wider type, since u64 would overflow for milliseconds around year 2554.

Using chrono crate (recommended)

// Cargo.toml: chrono = "0.4"
use chrono::Utc;

let secs = Utc::now().timestamp();
let ms   = Utc::now().timestamp_millis();

chrono is the standard date/time crate in the Rust ecosystem. timestamp() returns i64 seconds; timestamp_millis() returns i64 milliseconds.

Convert timestamp back to DateTime (chrono)

use chrono::{DateTime, Utc, TimeZone};

let dt: DateTime<Utc> = Utc.timestamp_opt(1708560000, 0).unwrap();
println!("{}", dt.to_rfc3339());

Reconstruct a DateTime from a Unix timestamp using chrono's TimeZone trait.

Note

Rust's std SystemTime uses u64 for seconds and u128 for milliseconds — both unsigned. chrono uses i64 (signed) to support dates before 1970. For production code, prefer chrono over manual Duration arithmetic.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter