Alex Garella
3rd October 2023
In Rust, the default way of working with dates and times is with the chrono crate. One of its notable features is the ability to format dates and times. Here's a quick dive into date and time formatting in Rust using chrono
.
First, add chrono
to your Cargo.toml
:
[dependencies]
chrono = "0.4"
To create a DateTime
object:
use chrono::{DateTime, Local, Utc};
fn main() {
let current_utc: DateTime<Utc> = Utc::now();
let current_local: DateTime<Local> = Local::now();
println!("{}", current_utc); // Outputs: 2023-10-03 13:37:44.609871 UTC
println!("{}", current_local); // Outputs: 2023-10-03 16:37:44.610032 +03:00
}
Using the to_rfc3339()
and format()
methods, you can represent DateTime
in various formats:
use chrono::{DateTime, Utc};
fn main() {
let current_utc: DateTime<Utc> = Utc::now();
let rfc_format: String = current_utc.to_rfc3339();
println!("{}", rfc_format); // Outputs: 2023-10-03T13:39:01.385491+00:00
}
use chrono::{DateTime, Local};
fn main() {
let current_local: DateTime<Local> = Local::now();
let custom_format = current_local.format("%Y-%m-%d %H:%M:%S");
println!("{}", custom_format); // Outputs: 2023-10-03 16:41:00
}
In the custom format:
%Y
represents the year.%m
represents the month.%d
represents the day.%H
represents the hour.%M
represents the minute.%S
represents the second.With chrono
, time formatting in Rust becomes simple and intuitive. The flexibility of custom formats ensures you can represent dates and times in any desired manner.