Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime serializers omitting milliseconds? [duplicate]

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?
like image 819
RPM1984 Avatar asked Oct 30 '25 14:10

RPM1984


1 Answers

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

like image 155
David Browne - Microsoft Avatar answered Nov 01 '25 06:11

David Browne - Microsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!