rfc_manager/serde_format/
rfc_3339.rs

1use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
2use serde::{self, Deserialize, Deserializer, Serializer};
3
4/// ref. https://serde.rs/custom-date-format.html
5pub fn serialize<S>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
6where
7    S: Serializer,
8{
9    // ref. https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html#method.to_rfc3339_opts
10    serializer.serialize_str(&dt.to_rfc3339_opts(SecondsFormat::Millis, true))
11}
12
13/// ref. https://serde.rs/custom-date-format.html
14pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
15where
16    D: Deserializer<'de>,
17{
18    let s = String::deserialize(deserializer)?;
19
20    // ref. https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html#method.parse_from_rfc3339
21    match DateTime::parse_from_rfc3339(&s).map_err(serde::de::Error::custom) {
22        Ok(dt) => Ok(Utc.from_utc_datetime(&dt.naive_utc())),
23        Err(e) => Err(e),
24    }
25}