Working with Dates and Time in Rust: From A to Z
Working with dates and time is one of the key tasks in developing any application: from web services to logging systems. In Rust, known for its safety and performance, working with dates is implemented through the powerful chrono library. In this article, we will cover all aspects of working with dates and time: from basic operations to complex manipulations with time zones.
1. Installing and Configuring the chrono Library
The chrono library is the de facto standard for working with dates and time in Rust. It provides a complete set of tools: from simple date objects to complex types with time zone awareness.
To get started, add the dependency to your Cargo.toml file:
[dependencies]chrono = "0.4"After that, import the necessary modules into your code:
use chrono::{NaiveDate, NaiveDateTime, DateTime, Utc, Local, Duration};use chrono::format::ParseError;2. Basic Data Types for Working with Dates
In chrono, there are several key types that cover all developer needs:
NaiveDate— a date without time and time zone (e.g., 2024-01-15).NaiveTime— a time without date and time zone (e.g., 14:30:00).NaiveDateTime— a combination of date and time without a time zone.DateTime<Tz>— a date and time with a specified time zone (e.g.,DateTime<Utc>orDateTime<Local>).
Let's look at an example of creating objects of each type:
// Creating a NaiveDatelet date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();println!("Date: {}", date); // 2024-01-15
// Creating a NaiveTimelet time = NaiveTime::from_hms_opt(14, 30, 0).unwrap();println!("Time: {}", time); // 14:30:00
// Creating a NaiveDateTimelet datetime = NaiveDateTime::new(date, time);println!("Date and time: {}", datetime); // 2024-01-15 14:30:00
// Creating a DateTime with UTC time zonelet utc_datetime = Utc::now();println!("Current UTC time: {}", utc_datetime);
// Creating a DateTime with local time zonelet local_datetime = Local::now();println!("Current local time: {}", local_datetime);3. Formatting and Parsing Dates
One of the most common tasks is converting dates to strings and back. chrono uses format strings similar to strftime from C.
Formatting a Date to a String
For formatting, use the .format() method:
use chrono::Utc;
let now = Utc::now();
// Standard ISO 8601 formatprintln!("ISO 8601: {}", now.format("%Y-%m-%dT%H:%M:%S%z"));
// Russian language formatprintln!("Russian format: {}", now.format("%d.%m.%Y %H:%M"));
// Only dateprintln!("Only date: {}", now.format("%A, %d %B %Y"));
// Output:// ISO 8601: 2024-01-15T14:30:00+0000// Russian format: 15.01.2024 14:30// Only date: Monday, 15 January 2024Main format specifiers:
%Y— year (4 digits)%m— month (01-12)%d— day (01-31)%H— hours (00-23)%M— minutes (00-59)%S— seconds (00-59)%z— time zone offset%A— full weekday name%B— full month name
Parsing a String into a Date
To convert a string into a date, use the parse_from_str() method:
use chrono::NaiveDate;use chrono::format::ParseError;
fn parse_date(dat