How can I get the current time in milliseconds?

How can I get the current time in milliseconds like I can in Java?

System.currentTimeMillis()

Solution 1:

Since Rust 1.8, you do not need to use a crate. Instead, you can use SystemTime and UNIX_EPOCH:

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

fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    println!("{:?}", since_the_epoch);
}

If you need exactly milliseconds, you can convert the Duration.

Rust 1.33

let in_ms = since_the_epoch.as_millis();

Rust 1.27

let in_ms = since_the_epoch.as_secs() as u128 * 1000 + 
            since_the_epoch.subsec_millis() as u128;

Rust 1.8

let in_ms = since_the_epoch.as_secs() * 1000 +
            since_the_epoch.subsec_nanos() as u64 / 1_000_000;

Solution 2:

If you just want to do simple timings with the milliseconds, you can use std::time::Instant like this:

use std::time::Instant;

fn main() {
    let start = Instant::now();

    // do stuff

    let elapsed = start.elapsed();

    // Debug format
    println!("Debug: {:?}", elapsed); 

    // Format as milliseconds rounded down
    // Since Rust 1.33:
    println!("Millis: {} ms", elapsed.as_millis());

    // Before Rust 1.33:
    println!("Millis: {} ms",
             (elapsed.as_secs() * 1_000) + (elapsed.subsec_nanos() / 1_000_000) as u64);
}

Output:

Debug: 10.93993ms
Millis: 10 ms
Millis: 10 ms

Solution 3:

You can use the time crate:

extern crate time;

fn main() {
    println!("{}", time::now());
}

It returns a Tm which you can get whatever precision you want.

Solution 4:

I've found a clear solution with chrono in coinnect:

use chrono::prelude::*;

pub fn get_unix_timestamp_ms() -> i64 {
    let now = Utc::now();
    now.timestamp_millis()
}

pub fn get_unix_timestamp_us() -> i64 {
    let now = Utc::now();
    now.timestamp_nanos()
}

Solution 5:

extern crate time;

fn timestamp() -> f64 {
    let timespec = time::get_time();
    // 1459440009.113178
    let mills: f64 = timespec.sec as f64 + (timespec.nsec as f64 / 1000.0 / 1000.0 / 1000.0);
    mills
}

fn main() {
    let ts = timestamp();
    println!("Time Stamp: {:?}", ts);
}

Rust Playground