How to get the current date and time in local and UTC in Rust example

This program prints the current date and time in the system and UTC timezone using the Chrono library to access timestamp-related information.

To begin, let’s create a new Rust project using the cargo command:

cargo new dateapp

Next, change the directory to dateapp:

cd dateapp

Add the Chrono dependency in the cargo.toml file.

[dependencies]
chrono = "0.4"

Now, run the cargo build command to install all dependencies.

cargo build

Let’s write the code to print the date in both local and UTC formats.

Rust Current Date and time in UTC and Local

  • Utc::now(): Returns a DateTime<Utc> object containing the UTC date and time.
  • Local::now(): Returns a DateTime<Local> object containing the system’s date and time.

Here is the example program

use chrono::{DateTime, Local, Utc};

fn main() {
    let utc: DateTime = Utc::now();
    let local: DateTime = Local::now();
    println!("Current Date and Time in UTC {:?}", utc);
    println!("Current Date and Time in System {:?}", utc);
}

Run the above code using cargo run.

PS A:\work\rust\dateapp> cargo run
   Compiling dateapp v0.1.0 (A:\work\rust\dateapp)
    Finished dev [unoptimized + debuginfo] target(s) in 1.56s
     Running `target\debug\dateapp.exe`
Current Date and Time in UTC 2022-04-29T10:53:01.715904300Z
Current Date and Time in System 2022-04-29T16:23:01.715941800+05:30

It displays the current date and time UTC and Local System time zones information