如何在Java中获得当前时间(以毫秒为单位)?
System.currentTimeMillis()
从Rust 1.8开始,您不需要使用板条箱。相反,你可以使用SystemTime
和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
。
let in_ms = since_the_epoch.as_millis();
let in_ms = since_the_epoch.as_secs() as u128 * 1000 +
since_the_epoch.subsec_millis() as u128;
let in_ms = since_the_epoch.as_secs() * 1000 +
since_the_epoch.subsec_nanos() as u64 / 1_000_000;
你可以使用time crate:
extern crate time;
fn main() {
println!("{}", time::now());
}
它返回一个Tm
,你可以得到你想要的任何精度。
如果你只想用毫秒做简单的计时,你可以像这样使用std::time::Instant
:
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);
}
输出:
Debug: 10.93993ms
Millis: 10 ms
Millis: 10 ms
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);
}
Java中的System.currentTimeMillis()
返回当前时间与1970年1月1日午夜之间的差异(以毫秒为单位)。
在Rust,我们有time::get_time()
,返回一个Timespec
,当前时间为秒,自1970年1月1日午夜起以纳秒为单位。
示例(使用Rust 1.13):
extern crate time; //Time library
fn main() {
//Get current time
let current_time = time::get_time();
//Print results
println!("Time in seconds {}\nOffset in nanoseconds {}",
current_time.sec,
current_time.nsec);
//Calculate milliseconds
let milliseconds = (current_time.sec as i64 * 1000) +
(current_time.nsec as i64 / 1000 / 1000);
println!("System.currentTimeMillis(): {}", milliseconds);
}