time icon indicating copy to clipboard operation
time copied to clipboard

`well-known` serde for `Vec<OffsetDateTime>`

Open kamulos opened this issue 2 years ago • 3 comments

I am porting my program from chrono to time. One thing I am stuck with is serializing a Vec<OffsetDateTime> with the rfc3339 format.

This seems like a small but very useful addition. Is this something that would be considered to be included?

kamulos avatar Mar 08 '22 16:03 kamulos

This is what just tried to use in the serialize_with attribute:

fn date_vec_ser<S: Serializer>(
    vec: &[OffsetDateTime],
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    let stringvec = vec
        .iter()
        .map(|odt| odt.format(&Rfc3339))
        .collect::<std::result::Result<Vec<String>, time::error::Format>>()
        .map_err(S::Error::custom)?;
    stringvec.serialize(serializer)
}

kamulos avatar Mar 08 '22 17:03 kamulos

I'm not going to say it's 100%, but I think this is reasonable.

jhpratt avatar Mar 08 '22 19:03 jhpratt

There is support for the well-known formats in serde_with, such that you can write this code and support other nestings.

#[serde_with::serde_as]
#[derive(Debug, serde::Deserialize)]
struct Data(
    #[serde_as(as = "Vec<time::format_description::well_known::Rfc3339>")]
    Vec<time::OffsetDateTime>
);

let v = serde_json::json!([
    "1997-11-21T01:55:06-06:00",
    "2000-01-21T05:55:06-06:00",
    "2020-03-21T09:55:06-06:00",
    "1997-11-21T23:55:06-06:00",
]);
let d: Data = serde_json::from_value(v).unwrap();
dbg!(d);

https://www.rustexplorer.com/b/kdutp7

jonasbb avatar Jul 20 '22 22:07 jonasbb