JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.63k stars 3.24k forks source link

Deserializing RFC3339 timestamp failes based on precision #2185

Open DC-jc opened 4 years ago

DC-jc commented 4 years ago

When deserializing timestamps formatted according to RFC3339 will normally return DateTime objects, but if the seconds-fraction ([time-secfrac] in the specification) exceeds 7 digits the timestamp will instead be deserialized as a string.

Expected behavior

From what I can tell DateTime is able to handle RFC3339 timestamps with arbitrary precision so I would expect DateTime to be returned every time but primarily I would expect the result to be consistent.

Actual behavior

//This will produce a DateTime object
Newtonsoft.Json.JsonConvert.DeserializeObject<object>("2019-08-13T11:28:30.8630322Z");

//This will produce a string object
Newtonsoft.Json.JsonConvert.DeserializeObject<object>("2019-08-13T11:28:30.45061395Z");
rafalkozik commented 4 years ago

This issue is quite interesting. DateTime.Parse is able to parse both values, while DateTime.ParseExact with "o" format fails as well.

I think that in this situation it might be worth parsing more digits (up to 20, as maximum length of date in iso format parsing is currently limited to 40 characters). The only thing that's needed is to round fraction based on the next digit.

I have created PR with proposed change. One notable behavior change is that "9999-12-31T23:59:59.99999999" throws now an exception instead of not parsing (as it's out of range for DateTime).

DC-jc commented 4 years ago

Thank you, this PR seems to fix my problem.

pmzara commented 3 years ago

I have the same issue with my project. Any idea when this PR will be pushed to release? Is there any workaround?