DEV Community

Thiago Massari Guedes
Thiago Massari Guedes

Posted on

1

Another way to deserialise DateTime in Rust

In a previous post, I wanted to deserialise a date from a Toml file and implemented the Deserialize trait for a type NaiveDate. When I was implementing metrics, I had to do it again, but implement serialise and deserialise for NaiveDate and I found another way, possibly simpler, to serialise and deserialise NaiveDate.

First: add derive support to your Cargo.toml

Inside dependencies, make sure that derive feature is enabled

[dependencies]
serde = { version = "1.0.198", features = ["derive"] }
Enter fullscreen mode Exit fullscreen mode

Second: In the struct containing the NaiveDate you want to serialise and deserialise, add #[serde(with = "naive_date_format")]. E.g.

use crate::metrics::naive_date_format;
// ...

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]  
pub struct PostCounter {  
    pub post_id: String,  
    pub total: u64,  
    pub origins: HashSet<String>,  
    #[serde(with = "naive_date_format")]
    pub stats_date: NaiveDate,  
}
Enter fullscreen mode Exit fullscreen mode

Third: Create naive_date_format function

You may figured already that naive_date_format is a function. This is a suggested implementation

mod naive_date_format {  
    use chrono::NaiveDate;  
    use serde::{self, Deserialize, Deserializer, Serializer};  

    const FORMAT: &str = "%Y-%m-%d";  

    /// Transforms a NaiveDate into a String
    pub fn serialize<S>(date: &NaiveDate, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {  
        let s = date.format(FORMAT).to_string();
        serializer.serialize_str(&s)
    }

    /// Transforms a String into a NaiveDate
    pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>  
        where
            D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        NaiveDate::parse_from_str(&s, FORMAT).map_err(serde::de::Error::custom)
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you need a conclusion, please read again the code before the conclusion.


Original post in the author's blog: Another way to deserialise DateTime in Rust

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs