How to Serialize and Deserialize Dates with Serde in Rust

Serialize and deserialize Rust dates with Serde by using the chrono crate and specific attribute annotations like ts_utc or iso8601.

Use the chrono crate with serde to handle date serialization and deserialization by deriving traits and annotating fields with format strings.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Event {
    #[serde(with = "chrono::serde::ts_utc")]
    timestamp: DateTime<Utc>,
}

This configuration serializes dates as Unix timestamps (integers) in UTC. For human-readable ISO 8601 strings, replace ts_utc with serde_with::rust::chrono::serde::ts_utc or use #[serde(with = "chrono::serde::iso8601")] if using the chrono feature set.