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.
It uses the Chrono library to access current timestamp-related information.
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 cargo.toml file
[dependencies]
chrono = "0.4"
Now, Run the cargo build command to install all dependencies.
cargo build
Let’s write a code for the printing date in local and UTC format.
Rust Current Date and time in
Utc::now()
: returns DateTime<Utc>
object that contains UTC date and time
Local::now()
: returns DateTime<Local>
object that contains System date and time
Here is an 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);
}
Running 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