问题
I have a time::Duration. How can I get the number of milliseconds represented by this duration as an integer? There used to be a num_milliseconds() function, but it is no longer available.
回答1:
Here is the solution I came up with, which is to multiply the seconds by a billion, add it to the nanoseconds, then divide by 1e6.
let nanos = timeout_duration.subsec_nanos() as u64;
let ms = (1000*1000*1000 * timeout_duration.as_secs() + nanos)/(1000 * 1000);
回答2:
Use time::Duration from the time crate on crates.io which provides a num_milliseconds() method.
回答3:
Since Rust 1.33.0, there is an as_millis() function:
use std::time::SystemTime;
fn main() {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("get millis error");
println!("now millis: {}", now.as_millis());
}
Since Rust 1.27.0, there is a subsec_millis() function:
use std::time::SystemTime;
fn main() {
let since_the_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("get millis error");
let seconds = since_the_epoch.as_secs();
let subsec_millis = since_the_epoch.subsec_millis() as u64;
println!("now millis: {}", seconds * 1000 + subsec_millis);
}
Since Rust 1.8, there is a subsec_nanos function:
let in_ms = since_the_epoch.as_secs() * 1000 +
since_the_epoch.subsec_nanos() as u64 / 1_000_000;
See also:
- How can I get the current time in milliseconds?
来源:https://stackoverflow.com/questions/36816072/how-do-i-get-a-duration-as-a-number-of-milliseconds-in-rust