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())}

Use NaiveDate instead of NaiveDateTime.


use chrono::naive::NaiveDate;
use chrono::Local;

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    date_only_no_datetime: NaiveDate,
}

fn main() {

    let f = vec![
        Foo {
        date_only_no_datetime: Local::now().date_naive(),
        },
        Foo {
        date_only_no_datetime: Local::now().date_naive(),
        },
        Foo {
        date_only_no_datetime: Local::now().date_naive(),
        },
        

    ]
    
    ;
    let jsn = serde_json::to_string_pretty(&f).unwrap() ;

    println!("{jsn}"  );

    let deser: Vec<Foo> = serde_json::from_str(&jsn).unwrap();

    println!("{deser:?}"  );


}
1 Like

??????
The output requested in post 1:
"2025-05-01"
is deserialized.
But, what you want for compare, filter, add/sub, etc. is serialized. (Then there are no worries about leap year and days per month. THEN you deserialize for readability, storage in CVS files, etcetera.

"Deserialization is the process whereby a lower-level format (e.g., that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure."

Cheers,

1 Like

Thanks.
All thighs work as I want..
But now have faced new problem. Sometimes (yesterday and today) app seems changes encoding of the json (UTF8) to ANSI and often panics :

called `Result::unwrap()` on an `Err` value: Custom { kind: InvalidData, error: Error("expected value", line: 1, column: 1) }

Very strange situation.

UPD:
app just reads (not writes, only de-serialization not serialization).