Serialize an ISO 8601 time/duration "Thhmmss-hhmm/PTmm" ie ("T063000-0600/PT10M") to a rust struct

264 Views Asked by At

I'm writing a fairly simple REST api, one of my objects will want to know a time of day and duration to be activated. I'm hoping I can serialize an ISO 8601 Time/Duration into a data members of a struct in rust using actix-web, serde and chrono, is this possible?

I've done some initial research into serde serilization and chrono, but I'm not finding much other than very basic datetime serialization. Not quite what I want to do.

1

There are 1 best solutions below

2
cdhowie On BEST ANSWER

Anything is possible, of course, but in this case you will have to do some of the lifting yourself or using another crate, because chrono's Duration type doesn't provide formatting or parsing utilities.

You can implement the time half quite easily. Note that chrono doesn't have a "time with timezone" type, so I will use NaiveTime and assume UTC.

use chrono::{NaiveTime, Duration};
use serde::Serialize;

struct TimeWithDuration {
    pub time: NaiveTime,
    pub duration: Duration,
}

impl Serialize for TimeWithDuration {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!(
            "{}/{}",
            self.time.format("T%H%M%SZ"),
            format_duration(self.duration),
        )
    }
}

fn format_duration(duration: Duration) -> impl Display {
    todo!()
}

format_duration is a placeholder function that should format the duration appropriately. You might consider looking into the iso8601-duration crate.