Rust 获取当前系统时间戳

一种是采用系统库timestamp1,一种是采用第三方库timestamp2,但是由于time库已经不在维护,所以推荐使用官方库。

目前rust的时间库为chrone

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

extern crate time;

fn timestamp2() -> i64 {
    let timespec = time::get_time();
    timespec.sec * 1000 + (timespec.nsec as f64 / 1000.0 / 1000.0) as i64
}

fn timestamp1() -> i64 {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    let ms = since_the_epoch.as_secs() as i64 * 1000i64 + (since_the_epoch.subsec_nanos() as f64 / 1_000_000.0) as i64;
    ms
}

fn main() {
    let ts1 = timestamp1();
    println!("TimeStamp1: {}", ts1);
    let ts2 = timestamp2();
    println!("TimeStamp2: {}", ts2);
}

不过虽然time库不在维护,又出现一个新的时间库chrone
而且用法更简单,推荐如下这种方式

use chrono::prelude::*;

extern crate chrono;

fn main() {
    let dt = Local::now();
    println!("dt: {}", dt);
    println!("dt: {}", dt.timestamp_millis());
}

官网地址:https://github.com/chronotope/chrono/

你可能感兴趣的:(Rust 获取当前系统时间戳)