Search code examples
c#.netjson.netserializationsystem.text.json

DateTime serializers omitting milliseconds?


I've noticed that both JSON.NET and System.Text.Json doesn't serialize the milliseconds of a datetime when the value is zero.

As in, i see values like: "3000-01-01T00:00:00" (no milliseconds), and "3000-01-01T00:00:00.999"

Here is a fiddle demonstrating the issue: https://dotnetfiddle.net/yi47EY

The issue is, we have clients that are breaking because they expect a consistent format (e.g always returning milliseconds, even when .000)

I found this reference: https://www.w3.org/TR/NOTE-datetime

Which states:

An adopting standard that permits fractions of a second must specify both the minimum number of digits (a number greater than or equal to one) and the maximum number of digits (the maximum may be stated to be "unlimited")."

So, does that mean:

  1. JSON.NET and System.Text.Json is breaking the specification, because we are sending different 'formats'? or
  2. We are adhering to the specification, but all clients should be flexible to deal with the different formats?

Solution

  • JSON.NET and System.Text.Json is breaking the specification, because we are sending different 'formats'?

    JSON isn’t an “adopting standard” as it does not reference ISO 8601, or prescribe any particular format for date and time. In JSON they are just strings. So serializers are free to represent dates in any way they like. Both serializers choose ISO 8601, and fractional seconds are not required and often useless extra bytes.

    This is the downside of JSON being radically simple.

    System.Text.Json has custom converters you can use to override the default behavior of the serializer: How to write custom converters for JSON serialization (marshalling) in .NET