如何以毫秒为单位获取当前时间?

163

我该如何在JavaScript中获取当前时间的毫秒数,就像在Java中一样?

System.currentTimeMillis()
8个回答

237
自Rust 1.8版本起,您无需使用crate。相反,您可以使用SystemTimeUNIX_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();

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;

6
为什么要使用系统时间而不是瞬时时间? - Andy Hayden
6
你可能需要重新阅读Instant的文档:该结构没有获取“秒数”的方法,只能测量两个瞬间之间的持续时间(或比较两个瞬间) - Shepmaster
1
根据文档,UNIX_EPOCH是1970.000,UTC。因此我认为您不需要考虑时区。 - Timmmm
1
@Dominic 如何安全、习惯地在数字类型之间进行转换?。可能,持续时间可以表示比64位更长的时间跨度。 - Shepmaster
1
@SergeyKaunov 我期望大多数人都会创建一个函数,但重要的是如何处理错误。有些人可能更喜欢默认值,有些人会引发panic!,而其他人可能会传播错误。没有一种通用的解决方案。 - Shepmaster
显示剩余5条评论

60

如果你只想用毫秒进行简单的计时,可以像这样使用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

还可参阅RFC问题1545,该问题旨在将as_millis添加到Duration中。 - robinst
如果你需要时间间隔,可以查看 https://doc.rust-lang.org/1.8.0/std/time/struct.Instant.html#method.duration_since。 - vinyll
导致 u128 不受支持。 - Pedro Paulo Amorim

22

你可以使用time crate

extern crate time;

fn main() {
    println!("{}", time::now());
}
它会返回一个Tm,你可以得到任何你想要的精度。

2
如果只是想测量相对时间,那么来自该包的 precise_time_... 函数也很相关。 - huon
1
你必须使用 time::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ácser
1
time::precise_time_ns() 和 time::precise_time_s() - tyoc213
7
此 crate 已被弃用,请使用 chrono crate 替代。 - Ondrej Slinták
2
我喜欢每一种编程语言中与时间相关的库都不断被弃用的情况。 - LLL
显示剩余2条评论

21
我在coinnect中使用chrono找到了一个清晰的解决方案:
use chrono::prelude::*;

pub fn get_unix_timestamp_ms() -> i64 {
    let now = Utc::now();
    now.timestamp_millis()
}

pub fn get_unix_timestamp_us() -> i64 {
    let now = Utc::now();
    now.timestamp_nanos()
}

12
如 @Shepmaster 所提到的,这是 Rust 中类似于 Java 的 System.currentTimeMillis() 的方法。
use std::time::{SystemTime, UNIX_EPOCH};

fn get_epoch_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis()
}

2
如果您想要更高的精度,可以使用以下代码(返回毫秒级别的小数):SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64() * 1000f64 - Venryx

7
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);
}

Rust Playground


这不会返回与System.currentTimeMillis()相同的值。 - josehzz
是的,它确实返回秒数。为了获得毫秒数,您必须将秒乘以1000并将nsec除以1000减去(正如其他答案所做的那样)。 - contradictioned

5
在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);
}

参考文献:Time crateSystem.currentTimeMillis()


1
箱子的链接无效。 - User

5
似乎有一个简单的一行代码可以得到一个非常接近Java的long类型的u128
let timestamp = std::time::UNIX_EPOCH.elapsed().unwrap().as_millis()

文档确实提到了与SystemTime对象相关的时钟漂移问题,但我认为这在这里并不适用,因为我们是根据一个很久以前的时间点进行检查。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接