Date and Time Formatting in Rust
Alex Garella
3 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.
Setting Up
First, add chrono to your Cargo.toml:
[dependencies]
chrono = "0.4" Creating a DateTime
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
} Formatting DateTime
Using the to_rfc3339() and format() methods, you can represent DateTime in various formats:
- RFC 3339 (ISO 8601) Format:
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
}
- Custom Formats:
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:
%Yrepresents the year.%mrepresents the month.%drepresents the day.%Hrepresents the hour.%Mrepresents the minute.%Srepresents the second.
Conclusion
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.