Unix Timestamp in Rust
In Rust, SystemTime::now().duration_since(UNIX_EPOCH) yields the time since the epoch as a Duration; call .as_secs() or .as_millis(). The chrono crate offers richer formatting via DateTime::from_timestamp.
Get & convert epoch time in Rust
use std::time::{UNIX_EPOCH, Duration};
let t = UNIX_EPOCH + Duration::from_secs(1700000000); // 2023-11-14T22:13:20.000Z
// chrono: DateTime::from_timestamp(1700000000, 0)Gotcha: duration_since returns a Result — it errors if the clock is before the epoch — so handle or unwrap deliberately.
Frequently asked questions
- How do I get the current Unix timestamp in Rust?
- SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() for seconds.
- How do I format a timestamp in Rust?
- Use the chrono crate: DateTime::from_timestamp(secs, 0) then .to_rfc3339().