如何以毫秒为单位获取当前时间? [英] How can I get the current time in milliseconds?
本文介绍了如何以毫秒为单位获取当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何像在 Java 中一样以毫秒为单位获取当前时间?
How can I get the current time in milliseconds like I can in Java?
System.currentTimeMillis()
推荐答案
从 Rust 1.8 开始,你不需要使用 crate.相反,您可以使用 SystemTime
和 UNIX_EPOCH
:
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);
}
如果你需要精确的毫秒,你可以转换Duration
.
If you need exactly milliseconds, you can convert the Duration
.
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;
这篇关于如何以毫秒为单位获取当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文