Epoch and Date Time Conversion in Rust

Rust a multi-paradigm programming language designed for performance and safety, especially safe concurrency. It provide many date time functions to handle date time functionality.

Here we will explain Rust date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in Rust

You can get the current timestamp using following.

use chrono::Utc;
let dt = Utc::now();
let timestamp: i64 = dt.timestamp();


Convert epoch or Unix timestamp to date in Rust

You can convert the timestamp to date using below.

extern crate chrono;
use chrono::prelude::*;
fn main() {
let timestamp = "1625383193".parse::().unwrap();
let naive = NaiveDateTime::from_timestamp(timestamp, 0);
let datetime: DateTime = DateTime::from_utc(naive, Utc);
let newdate = datetime.format("%Y-%m-%d %H:%M:%S");
println!("{}", newdate);
}


Convert date to epoch or unix timestamp in Rust

You can convert date to unix timestamp using below.

use chrono::{NaiveDate, NaiveDateTime};
fn main() {
let dateTime: NaiveDateTime = NaiveDate::from_ymd(2021, 04, 07).and_hms(17, 33, 44);
println!(" Timestamp is : ", dateTime.timestamp());
}



More about date time in Rust