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

时间:2014-10-27 17:34:15

标签: rust

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

System.currentTimeMillis()

7 个答案:

答案 0 :(得分:58)

从Rust 1.8开始,您不需要使用板条箱。相反,您可以使用SystemTimeUNIX_EPOCH

import Data.Function (fix)

idempotently :: Eq a => (a -> a) -> a -> a
idempotently = fix $ \i f a ->
  let a' = f a
  in if a' == a then a else i f a'

如果您需要精确的毫秒数,则可以转换Duration

Rust 1.33

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

Rust 1.27

let in_ms = since_the_epoch.as_millis();

Rust 1.8

let in_ms = since_the_epoch.as_secs() as u128 * 1000 + 
            since_the_epoch.subsec_millis() as u128;

答案 1 :(得分:18)

您可以使用time crate

extern crate time;

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

它会返回Tm,您可以获得所需的精度。

答案 2 :(得分:17)

如果你只想用毫秒做简单的时间,你可以像这样使用std::time::Instant

use std::time::Instant;

fn main() {
    let start = Instant::now();

    // do stuff

    let elapsed = start.elapsed();
    // debug format:
    println!("{:?}", elapsed);
    // or format as milliseconds:
    println!("Elapsed: {} ms",
             (elapsed.as_secs() * 1_000) + (elapsed.subsec_nanos() / 1_000_000) as u64);

}

答案 3 :(得分: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

答案 4 :(得分:5)

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

答案 5 :(得分: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()

答案 6 :(得分:0)

正如@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()
}