如何在Rust中获取以毫秒为单位的当前时间戳| Rust纪元时间示例

5,849 阅读1分钟

在这篇文章中,你将学习到在Rust中获取当前纪元时间戳的多种方法。

epoch时间是Unix风格的,以1971年1月1日以来的毫秒为单位,这意味着它返回一个以毫秒为单位的长数字。它是纪元时间Unix时间戳

Rust提供的Date 对象提供了与日期和时间相关的东西。

SystemTime结构提供了实用函数或SystemClock。

SystemTime::now() 返回包含当前时间的SystemTime对象。duration_since 返回当前时间与Unix时间之间的差异持续时间。as_millis 函数返回毫秒总数。

下面是一个例子

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let time = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis();
    println!("{}", time);
}

输出

1651227581881

下面的程序获得当前时间:

  • 使用as_nanos()函数计算纳秒。
  • 微秒,使用as_micros()函数
  • 秒,使用as_secs()函数
  • 使用as_secs_f64()函数得到持续时间为f64的秒数
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    println!("Current Micro Seconds: {}", time.as_micros());
    println!("Current Nano Seconds:  {}", time.as_nanos());
    println!("Current Seconds: {}", time.as_secs());
    println!("Current Seconds in f64: {}", time.as_secs_f64());
}

输出

Current Micro Seconds: 1651227748258206
Current Nano Seconds:  1651227748258206700
Current Seconds: 1651227748
Current Seconds in f64: 1651227748.2582066

另一种方法是使用Chrono库。首先使用utc::now() now.timestamp()函数获得utc当前时间,返回i64

use chrono::prelude::*;

fn main() {
    let now = Utc::now();
    let ts: i64 = now.timestamp();
 
    println!("{}", ts);
}

输出

1651225235661