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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…