Preamble
By default the JSON serializer supports the ISO DateTime Standard by the means of the IsoDateTimeConverter
With some additional customization we can force that all Datetimes are in UTC (http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization)
jsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc
This again works as expected with 1972-09-18T02:29:12.264513Z
and 1972-09-18T04:29:12.264513+02:00
both equating to 1972-09-18 02:29:12 AM
after serialization.
Problem
Unfortunately, however, leaving off the time-zone offset suffix also successfully serializes. So 1972-09-18T04:29:12.264513
equates to 1972-09-18 04:29:12 AM
UTC.
The problem here is that we've made the assumption that the consumer knows about date formats and understands (based on our documentation) that dates are always assumed as UTC.
The Question
Is there a way to force the serialization to fail if the time-zone offset suffix is missing so that we are not making any assumptions?
The title of this question should say "Strictly enforce RFC 3339 date-time ..."
That's because ISO 8601 actually doesn't require the time-zone designator in the values. The format that requires it is RFC 3339 date-time. RFC 3339 is a subset of ISO8601 and is also the one used widely over the Internet (JSON Schema, OpenAPI), which is also the RFC 3339's goal: in their own words, the format "SHOULD be used in new protocols on the Internet", and the detailed justification is that "Since interpretation of an unqualified local time zone will fail in approximately 23/24 of the globe, the interoperability problems of unqualified local time are deemed unacceptable for the Internet."
As for the solution for the Newtonsoft JSON library (and consequently ASP.NET and the many framework that use it nowadays), I have raised the issue #1631 to make following the RFC 3339 recommendation simpler but, for now, one needs to resort to writing their own date time converter.
I just looked into Json.NET code and I'm affraid that's not possible (or at least extremly difficult because of need to override JsonTextReader
/JsonTextWriter
) to fail if time-zone offset suffix is omitted. All code related to parsing and serializing various data types is internal.
Below are links to places where magic is hapenning:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With