Want to deserialize a date

⚓ Rust    📅 2025-05-01    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 111 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Want to deserialize a date

At least I have found how to serialize dates.
Now :

  1. how to de-serialize it (date) ?
    (all chatgpt, google, internet, etc. examples do not compile, Rust docs hard to understand, written by experts for experts )
  2. how to de-serialize its (dates only) having ability to work with them: to compare, to filter, to add/sub, etc.
    let date_today : ????????? = ????????? ;
  3. or maybe there is alternative more intuitive crate ?

use chrono::naive::NaiveDateTime;
use chrono::Local;

use serde::{Serialize, Serializer};

#[derive(Serialize)]
struct Foo {
    #[serde(serialize_with = "serialize_date_only_no_datetime")]
    date_only_no_datetime: NaiveDateTime,
}

fn serialize_date_only_no_datetime<S>(v: &NaiveDateTime, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{    s.collect_str(&v.format("%Y-%m-%d"     ))      }

fn main() {

    let f = vec![
        Foo {        date_only_no_datetime: Local::now().naive_local(),        },
        Foo {        date_only_no_datetime: Local::now().naive_local(),        },
        Foo {        date_only_no_datetime: Local::now().naive_local(),        },
        
    ]
    
    ;
    let jsn = serde_json::to_string_pretty(&f).unwrap() ;

    println!("{jsn}"  );


}

(Playground)

Output:

[  {    "date_only_no_datetime": "2025-05-01"  },
  {    "date_only_no_datetime": "2025-05-01"  },
  {    "date_only_no_datetime": "2025-05-01"  }]

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.22s
     Running `target/debug/playground`

Here is something, not-working (as usual) snippet,
I do not understand what is going on and I cannot fix it

use chrono::{NaiveDate, NaiveDateTime};
use serde::{de::Deserializer, Deserialize, Serialize};

#[derive(/* Serialize, */  Deserialize, Debug)]
pub struct Event {
    // #[serde(deserialize_with = "naive_date_time_to_naive_date")]
    #[serde_as(as = "FromInto<NaiveDateTime>")]
      end: NaiveDate,
    // #[serde(deserialize_with = "naive_date_time_to_naive_date")]
    #[serde_as(as = "FromInto<NaiveDateTime>")]
    start: NaiveDate,
}

fn naive_date_time_to_naive_date<'de, D>(d: D) -> Result<NaiveDate, D::Error>
where
    D: Deserializer<'de>,
{ Ok(NaiveDateTime::deserialize(d)?.into())}

2 posts - 2 participants

Read full topic

🏷️ rust_feed