architect_api/utils/
chrono.rs

1//! Custom serializer/deserializer for chrono::DateTime<Utc>
2
3use crate::json_schema_is_string;
4use anyhow::{anyhow, Result};
5use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
6use serde_with::serde_conv;
7use std::str::FromStr;
8
9serde_conv!(
10    pub DateTimeOrUtc,
11    DateTime<Utc>,
12    format_datetime_or_utc,
13    parse_datetime_or_utc
14);
15
16fn format_datetime_or_utc(dt: &DateTime<Utc>) -> String {
17    dt.to_rfc3339()
18}
19
20fn parse_datetime_or_utc(s: &str) -> Result<DateTime<Utc>> {
21    // First try parsing as RFC3339 (with timezone)
22    if let Ok(dt) = DateTime::from_str(s) {
23        return Ok(dt);
24    }
25
26    // If that fails, try parsing as NaiveDateTime (without timezone) and assume UTC
27    match NaiveDateTime::from_str(s) {
28        Ok(naive_dt) => Ok(Utc.from_utc_datetime(&naive_dt)),
29        Err(e) => Err(anyhow!(
30            "Failed to parse as DateTime<Utc> (with or without timezone): {} - {}",
31            s,
32            e
33        )),
34    }
35}
36
37json_schema_is_string!(DateTimeOrUtc, "date-time");