How to get epoch time in Rust?

Asked 1 day ago Modified 1 day ago Viewed 12 times

How can I get the current system epoch time in milliseconds/seconds (and to a lesser extent nanoseconds and microseconds) in Rust?

1
w
44
1 Answer
Sort by
Posted 1 day ago Modified 1 day ago

To get the current epoch time in Rust you can use SystemTime::now() along with .duration_since and UNIX_EPOCH.

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let now = SystemTime::now();
    let duration_since_epoch = now.duration_since(UNIX_EPOCH).expect("Time before UNIX_EPOCH");

    let nanos: u128 = duration_since_epoch.as_nanos();
    let micros: u128 = duration_since_epoch.as_micros();
    // These two are probably what most are looking for
    let millis: u128 = duration_since_epoch.as_millis();
    let secs: u64 = duration_since_epoch.as_secs();

    println!("Epoch time in nanoseconds: {}, microseconds: {}, milliseconds: {}, seconds: {}", nanos, micros, millis, secs);
}

Also, if you are trying to measure elapsed time for benchmarking (or some similar use case), you may want to consider using Rust's Instant over SystemTime.

0
J
J
99

Your Answer

You Must Log In or Sign Up to Answer Questions