How to Get Current Timestamp in Milliseconds in Rust| Rust epoch time example
In this post, You will learn multiple ways to get the current epoch timestamp in Rust.
epoch time is Unix style in milliseconds since 01/01/1971, which means it returns a long number in milliseconds. It is epoch time or Unix timestamp
Rust provides the Date
object provides the date and time-related things.
Rust current time in Milliseconds
- using SystemTime
SystemTime struct provides a utility function or SystemClock.
SystemTime::now() returns SystemTime object that contains current time .
duration_since
returns the Duration of difference between the current time and Unix Time.
as_millis
function return the total number of a millisecond.
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 below program get the current time.
- nano seconds using as_nanos() function
- Micro seconds using as_micros() function
- seconds using as_secs() function
- seconds in duration f64 using as_secs_f64() function
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 way using chrono library.
First get utc current time using utc::now()
now.timestamp() function returns the i64
use chrono::prelude::*;
fn main() {
let now = Utc::now();
let ts: i64 = now.timestamp();
println!("{}", ts);
}
Output:
1651225235661