How to Handle Dates and Times with Serde in Rust

Enable the serde feature in chrono and derive Serialize/Deserialize to handle dates.

Serde does not handle dates and times by default because chrono types do not implement Serde traits out of the box. You must enable the serde feature in the chrono crate and use #[derive(Serialize, Deserialize)] on your structs to automatically serialize and deserialize DateTime fields.

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

#[derive(Serialize, Deserialize)]
struct Event {
    name: String,
    timestamp: DateTime<Utc>,
}

fn main() {
    let event = Event {
        name: "Launch".to_string(),
        timestamp: Utc::now(),
    };
    let json = serde_json::to_string(&event).unwrap();
    println!("{json}");
}