How to Get Current Timestamp in Milliseconds in Rust| Rust epoch time example

In this post, you will learn multiple ways to obtain the current epoch timestamp in Rust.

The epoch time, also known as Unix timestamp, represents the number of milliseconds since 01/01/1970. It returns a long number representing milliseconds.

Rust provides the SystemTime struct to handle date and time-related operations.

Rust: Current Time in Milliseconds

  • using SystemTime

The SystemTime struct offers utility functions for accessing the system clock.

  • SystemTime::now() returns a SystemTime object representing the current time.
  • duration_since(UNIX_EPOCH) calculates the duration between the current time and the Unix epoch.
  • as_millis() returns the total number of milliseconds.

Here is an example

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

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

Output:

1651227581881

The following program retrieves various time units:

  • nanoseconds using as_nanos()
  • microseconds using as_micros()
  • seconds using as_secs()
  • seconds in f64 using as_secs_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());
}

Output:

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

Another approach is to use the Chrono library.

First, obtain the current UTC time using Utc::now(). now.timestamp() function returns the i64 type data.

use chrono::prelude::*;

fn main() {
    let now = Utc::now();
    let ts: i64 = now.timestamp();

    println!("{}", ts);
}

Output:

1651225235661

Conclusion

In Summary, These native methods and library provides multiple ways to get Unix Timestamp.