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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay