Convert Dates and Times with Rust Date Tool
P

PixelPioneer 数字先驱

time convert
date tool
2025-09-17
Convert Dates and Times with Rust Date Tool

Rust DateTime Handling with Chrono

Rust datetime operations

Basic DateTime Operations

Rust's chrono crate provides robust datetime handling. Here are essential operations:

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

// Get current timestamp
let now = Utc::now();
println!("Current UTC: {}", now);

// Parse date string
let dt = NaiveDateTime::parse_from_str("2023-01-15 14:30:00", "%Y-%m-%d %H:%M:%S")?;
println!("Parsed datetime: {}", dt);

// Convert to timestamp
let timestamp = dt.timestamp();
println!("Unix timestamp: {}", timestamp);

Timezone Conversions

Handle timezone-aware datetimes and daylight saving time:

use chrono_tz::America::New_York;

// Convert UTC to local time
let utc_time = DateTime::<Utc>::from_utc(dt, Utc);
let local_time = utc_time.with_timezone(&Local);
println!("Local time: {}", local_time);

// Convert between timezones
let ny_time = utc_time.with_timezone(&New_York);
println!("New York time: {}", ny_time);

Formatting and Parsing

Custom date formats and ISO 8601 handling:

// Custom format parsing
let custom_date = NaiveDateTime::parse_from_str("15-Jan-2023 2:30PM", "%d-%b-%Y %I:%M%p")?;

// ISO 8601 parsing
let iso_date = DateTime::parse_from_rfc3339("2023-01-15T14:30:00-05:00")?;

// Formatting
println!("Formatted: {}", now.format("%Y/%m/%d %H:%M:%S"));

Date Arithmetic

Perform calculations with dates:

use chrono::Duration;

// Add days to date
let new_date = now.checked_add_signed(Duration::days(7)).unwrap();

// Calculate difference
let diff = new_date.signed_duration_since(now);
println!("Difference: {} days", diff.num_days());

// Compare dates
if new_date > now {
    println!("Future date");
}

Best Practices

  1. Always use DateTime<Utc> for storage
  2. Convert to local time only for display
  3. Handle DST transitions with chrono-tz
  4. Use checked_ methods for arithmetic to avoid panics
  5. Prefer RFC 3339 (ISO 8601) for serialization
// Safe arithmetic
match now.checked_add_signed(Duration::days(365)) {
    Some(future) => println!("Next year: {}", future),
    None => println!("Date overflow"),
}

For production systems, consider the newer time crate for improved performance and API design, especially if you don't need full timezone database support.