chrono
chrono copied to clipboard
Parsing NaiveDate from json with added time fails
The documentation for NaiveDate::parse_from_str
states that it is very relaxed in parsing all sorts of formats. Unfortunately this does not pass over to the Json serialization strategy using Serde. The following example with unit test will fail with the error:
mydata::tests::deserialize_end_date_with_time_fails' panicked at 'called `Result::unwrap()` on an `Err` value: Error("trailing input", line: 1, column: 30)', src\mydata.rs:21:47
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Serialize, Deserialize)]
pub struct MyData {
date: NaiveDate,
}
mod tests {
use super::*;
use serde_json::Result;
#[test]
fn deserialize_end_date_with_time_fails() {
let json = r#"{"date":"2021-11-19T23:02:23Z"}"#;
let expected_data = MyData {
date: NaiveDate::from_ymd(2021, 11, 19),
};
let data = serde_json::from_str(json).unwrap();
assert_eq!(expected_data, data);
}
}
chrono: 0.4.19 serde: 1.0.130 serde_json: 1.0.71