Hello.
I am looking to deserialize json dates to a struct of dates. I am comparing dates between events and using chrono with the NaiveDate for this. The data looks to be in the format of a DateTime. If I use the NaiveDate I get an error for trailing data when it parses it:
Error: Error("trailing input", line: 1, column: 675)
The code is:
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct Event {
end: NaiveDate,
start: NaiveDate,
}
pub fn process(events: Vec<Event>, start_date: NaiveDate, end_date: NaiveDate) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
let events = filter_range(events, start_date, end_date);
Ok(events)
}
fn filter_range(events: Vec<Event>, start_date: NaiveDate, end_date: NaiveDate) -> Vec<Event> {
events.into_iter().filter(|event: &Event| {
(event.start >= start_date && event.start <= end_date) || (event.end >= start_date && event.end <= end_date)
}).collect()
}
The data when parsed with a DateTime looks like this:
Event {
end: 2024-11-03T16:00:00Z,
start: 2024-11-01T16:00:00Z,
},
I would like the output to be:
Event {
end: 2024-11-03,
start: 2024-11-01,
},
How can I easily convert to a Date in the format of "yyyy-mm-dd" without needing to convert in the filter function? I need to pipe the data to a few functions for other fields so don't want to convert in the specific filter function. Ideally an annotation with a type from the json would be ideal but I have errors about data type mismatches if using NaiveDateTime and NaiveDate.
I have looked at annotations using serde_with and serde_as and also custom serializing and deserializing but haven't found anything that worked.
Any help is much appreciated.