The chrono crate provides the NaiveDateTime and DateTime types for handling dates and times, with DateTime<Tz> being the standard choice for timezone-aware operations. You typically create instances using the from_str method for parsing or the now() method for the current time, then format or manipulate them using the format method and arithmetic operators.
First, add the crate to your Cargo.toml:
[dependencies]
chrono = "0.4"
Here is a practical example showing how to parse a string, get the current time, and perform basic formatting and arithmetic:
use chrono::{DateTime, NaiveDateTime, Utc, Local, TimeZone};
fn main() {
// 1. Parse a date string (ISO 8601 format)
let parsed: NaiveDateTime = "2023-10-27 14:30:00".parse().unwrap();
println!("Parsed naive: {}", parsed);
// 2. Get current time in UTC and Local timezone
let now_utc: DateTime<Utc> = Utc::now();
let now_local: DateTime<Local> = Local::now();
println!("UTC: {}", now_utc.format("%Y-%m-%d %H:%M:%S"));
println!("Local: {}", now_local.format("%Y-%m-%d %H:%M:%S"));
// 3. Convert between timezones
let utc_to_local = now_utc.with_timezone(&Local);
println!("Converted to local: {}", utc_to_local);
// 4. Arithmetic: Add 24 hours to a DateTime
let tomorrow = now_utc + chrono::Duration::hours(24);
println!("Tomorrow: {}", tomorrow);
// 5. Custom formatting
let formatted = now_utc.format("%A, %B %d, %Y at %I:%M %p").to_string();
println!("Formatted: {}", formatted);
}
Key patterns to remember:
- Use
NaiveDateTimewhen you don't care about timezones (e.g., storing a date in a database without context). - Use
DateTime<Tz>(whereTzisUtc,Local, or a specificFixedOffset) for any operation involving real-world time or timezone conversion. - Parsing requires the input string to match the expected format; use
parse()for ISO 8601 orDateTime::parse_from_str()with a custom format string for others. - Formatting uses the same syntax as C's
strftime(e.g.,%Yfor year,%mfor month). - Arithmetic is done via
Durationfrom thestd::timemodule orchrono::Durationfor more precise control.
Avoid mixing NaiveDateTime and DateTime directly; always convert to a timezone-aware type before performing operations that depend on local time or daylight saving rules.