Skip to main content

serde_datetime/chrono/
ts_float_microseconds.rs

1use core::fmt;
2
3use chrono::{DateTime, Datelike as _, NaiveDate, TimeZone as _, Timelike as _, Utc};
4use serde::{de, ser};
5
6use super::lib_copy::serde_from;
7
8pub(crate) struct FloatMicroSecondsTimestampVisitor;
9
10pub fn serialize<S>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
11where
12    S: ser::Serializer,
13{
14    let f64 = dt.timestamp() as f64 + f64::from(dt.timestamp_subsec_micros()) / 1_000_000_f64;
15    serializer.serialize_f64(f64)
16}
17
18pub fn deserialize<'de, D>(d: D) -> Result<DateTime<Utc>, D::Error>
19where
20    D: de::Deserializer<'de>,
21{
22    d.deserialize_f64(FloatMicroSecondsTimestampVisitor)
23        .map(|dt| dt.with_timezone(&Utc))
24}
25
26impl<'de> de::Visitor<'de> for FloatMicroSecondsTimestampVisitor {
27    type Value = DateTime<Utc>;
28
29    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
30        formatter.write_str("a unix timestamp in float microseconds")
31    }
32
33    /// Deserialize a timestamp in float microseconds since the epoch
34    fn visit_i64<E>(self, value: i64) -> Result<DateTime<Utc>, E>
35    where
36        E: de::Error,
37    {
38        serde_from(Utc.timestamp_opt(value, 0), &value)
39    }
40
41    /// Deserialize a timestamp in float microseconds since the epoch
42    fn visit_u64<E>(self, value: u64) -> Result<DateTime<Utc>, E>
43    where
44        E: de::Error,
45    {
46        serde_from(Utc.timestamp_opt(value as i64, 0), &value)
47    }
48
49    /// Deserialize a timestamp in float microseconds since the epoch
50    fn visit_f64<E>(self, value: f64) -> Result<DateTime<Utc>, E>
51    where
52        E: de::Error,
53    {
54        serde_from(
55            Utc.timestamp_opt(
56                value as i64,
57                ((value * 1_000_000_f64) as u64 % 1_000_000) as u32,
58            ),
59            &value,
60        )
61        .map(|dt| {
62            DateTime::from_naive_utc_and_offset(
63                NaiveDate::from_ymd_opt(dt.year(), dt.month(), dt.day())
64                    .expect("")
65                    .and_hms_micro_opt(dt.hour(), dt.minute(), dt.second(), dt.nanosecond())
66                    .expect(""),
67                Utc,
68            )
69        })
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use chrono::{DateTime, NaiveDate, Utc};
76    use serde::{Deserialize, Serialize};
77    use serde_json::json;
78
79    use crate::chrono::ts_float_microseconds;
80
81    #[test]
82    fn test_ts_float_microseconds() -> Result<(), serde_json::Error> {
83        #[derive(Deserialize, Serialize, Debug)]
84        struct S {
85            #[serde(with = "ts_float_microseconds")]
86            time: DateTime<Utc>,
87        }
88
89        //
90        let s: S = serde_json::from_str(r#"{ "time": 1609459200.999999 }"#)?;
91        assert_eq!(
92            s.time,
93            DateTime::<Utc>::from_naive_utc_and_offset(
94                NaiveDate::from_ymd_opt(2021, 1, 1)
95                    .expect("")
96                    .and_hms_micro_opt(0, 0, 0, 999999)
97                    .expect(""),
98                Utc
99            )
100        );
101
102        let s: S = serde_json::from_str(r#"{ "time": 1609459200 }"#)?;
103        assert_eq!(
104            s.time,
105            DateTime::<Utc>::from_naive_utc_and_offset(
106                NaiveDate::from_ymd_opt(2021, 1, 1)
107                    .expect("")
108                    .and_hms_micro_opt(0, 0, 0, 0)
109                    .expect(""),
110                Utc
111            )
112        );
113
114        let s: S = serde_json::from_str(r#"{ "time": 1609459200.000001 }"#)?;
115        assert_eq!(
116            s.time,
117            DateTime::<Utc>::from_naive_utc_and_offset(
118                NaiveDate::from_ymd_opt(2021, 1, 1)
119                    .expect("")
120                    .and_hms_micro_opt(0, 0, 0, 1)
121                    .expect(""),
122                Utc
123            )
124        );
125
126        //
127        let s = S {
128            time: DateTime::from_naive_utc_and_offset(
129                NaiveDate::from_ymd_opt(2021, 1, 1)
130                    .expect("")
131                    .and_hms_micro_opt(0, 0, 0, 999999)
132                    .expect(""),
133                Utc,
134            ),
135        };
136        assert_eq!(
137            serde_json::to_value(s)?,
138            json!({ "time": 1609459200.999999 })
139        );
140
141        let s = S {
142            time: DateTime::from_naive_utc_and_offset(
143                NaiveDate::from_ymd_opt(2021, 1, 1)
144                    .expect("")
145                    .and_hms_micro_opt(0, 0, 0, 0)
146                    .expect(""),
147                Utc,
148            ),
149        };
150        assert_eq!(
151            serde_json::to_value(s)?,
152            json!({ "time": 1609459200.000000 })
153        );
154
155        let s = S {
156            time: DateTime::from_naive_utc_and_offset(
157                NaiveDate::from_ymd_opt(2021, 1, 1)
158                    .expect("")
159                    .and_hms_micro_opt(0, 0, 0, 1)
160                    .expect(""),
161                Utc,
162            ),
163        };
164        assert_eq!(
165            serde_json::to_value(s)?,
166            json!({ "time": 1609459200.000001 })
167        );
168
169        Ok(())
170    }
171}