How to Use the chrono Crate in Rust

The `chrono` crate provides a robust set of date and time types, with `NaiveDateTime` for timezone-agnostic calculations and `DateTime` for timezone-aware operations.

The chrono crate provides a robust set of date and time types, with NaiveDateTime for timezone-agnostic calculations and DateTime for timezone-aware operations. You typically create instances using constructors like from_ymd_opt or now(), and manipulate them using methods like checked_add_days or formatting via format().

First, add the dependency to your Cargo.toml:

[dependencies]
chrono = "0.4"

Here is a practical example showing how to create a specific date, calculate a future date, and format the output:

use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Local};

fn main() {
    // Create a naive date (no timezone)
    let date = NaiveDate::from_ymd_opt(2023, 10, 25)
        .expect("Invalid date");

    // Create a naive datetime
    let naive_dt = NaiveDateTime::new(
        date,
        chrono::NaiveTime::from_hms_opt(14, 30, 0).unwrap()
    );

    // Calculate a date 5 days in the future
    let future = naive_dt
        .checked_add_days(chrono::Duration::days(5))
        .expect("Overflow");

    println!("Original: {}", naive_dt.format("%Y-%m-%d %H:%M"));
    println!("Future:   {}", future.format("%Y-%m-%d %H:%M"));

    // Get current local time (timezone-aware)
    let now = Local::now();
    println!("Current Local Time: {}", now.format("%R"));
}

Key things to remember: always use the _opt constructors (like from_ymd_opt) which return Option instead of panicking on invalid dates, and prefer checked_add_days over direct arithmetic to avoid overflow errors. For timezone handling, use Local for the system time or Utc for Coordinated Universal Time. If you need to parse strings, use DateTime::parse_from_str with a format string matching your input, or NaiveDateTime::parse_from_str for naive times.

use chrono::{DateTime, NaiveDateTime, Utc};

let parsed: DateTime<Utc> = DateTime::parse_from_rfc3339("2023-10-25T14:30:00Z")
    .expect("Invalid RFC3339 format");

let naive_parsed: NaiveDateTime = NaiveDateTime::parse_from_str(
    "2023-10-25 14:30:00",
    "%Y-%m-%d %H:%M:%S"
).expect("Invalid format");

Be aware that chrono is currently in maintenance mode; for new projects requiring high performance or strict correctness, consider time or jiff as modern alternatives, but chrono remains the standard for general-purpose date/time work in the Rust ecosystem.