我该如何在JavaScript中获取当前时间的毫秒数,就像在Java中一样?
System.currentTimeMillis()
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;
如果你只想用毫秒进行简单的计时,可以像这样使用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
u128
不受支持。 - Pedro Paulo Amorim你可以使用time crate:
extern crate time;
fn main() {
println!("{}", time::now());
}
它会返回一个Tm
,你可以得到任何你想要的精度。precise_time_...
函数也很相关。 - huontime::now_utc()
或者 time::get_time()
,因为Java的System.currentTimeMillis()
返回的是UTC时间。我会这样写:let timespec = time::get_time(); let mills = timespec.sec + timespec.nsec as i64 / 1000 / 1000;
- Nándor Krácserchrono
crate 替代。 - Ondrej SlintákSystem.currentTimeMillis()
的方法。use std::time::{SystemTime, UNIX_EPOCH};
fn get_epoch_ms() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
}
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64() * 1000f64
- Venryxextern 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);
}
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);
}
long
类型的u128
。let timestamp = std::time::UNIX_EPOCH.elapsed().unwrap().as_millis()
Instant
的文档:该结构没有获取“秒数”的方法,只能测量两个瞬间之间的持续时间(或比较两个瞬间)。 - ShepmasterUNIX_EPOCH
是1970.000,UTC。因此我认为您不需要考虑时区。 - Timmmmpanic!
,而其他人可能会传播错误。没有一种通用的解决方案。 - Shepmaster