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

问题描述 投票:40回答:6

如何在Java中获得当前时间(以毫秒为单位)?

System.currentTimeMillis()
rust
6个回答
64
投票

从Rust 1.8开始,您不需要使用板条箱。相反,你可以使用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

Rust 1.33

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;

18
投票

你可以使用time crate

extern crate time;

fn main() {
    println!("{}", time::now());
}

它返回一个Tm,你可以得到你想要的任何精度。


17
投票

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

6
投票
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


6
投票

我在chrono找到了coinnect的明确解决方案:

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

4
投票

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()

© www.soinside.com 2019 - 2024. All rights reserved.