rustical_ical/
timestamp.rs

1use chrono::{DateTime, NaiveDateTime, Utc};
2use derive_more::derive::Deref;
3use rustical_xml::{ValueDeserialize, ValueSerialize};
4
5const UTC_DATE_TIME: &str = "%Y%m%dT%H%M%SZ";
6
7#[derive(Debug, Clone, Deref, PartialEq, Eq, Hash)]
8pub struct UtcDateTime(pub DateTime<Utc>);
9
10impl ValueDeserialize for UtcDateTime {
11    fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
12        let input = <String as ValueDeserialize>::deserialize(val)?;
13        Ok(Self(
14            NaiveDateTime::parse_from_str(&input, UTC_DATE_TIME)
15                .map_err(|_| {
16                    rustical_xml::XmlError::InvalidValue(rustical_xml::ParseValueError::Other(
17                        "Could not parse as UTC timestamp".to_owned(),
18                    ))
19                })?
20                .and_utc(),
21        ))
22    }
23}
24
25impl ValueSerialize for UtcDateTime {
26    fn serialize(&self) -> String {
27        format!("{}", self.0.format(UTC_DATE_TIME))
28    }
29}