Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

rust - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...