When serializing DateTime
or DateTimeOffset
, I'm getting inconsistent results depending on second fraction. If fraction == 0
, second part is 00
, yet if fraction > 0
, second part is 00.999
.
class MyDateHoldingThingy
{
public DateTime DateTime { get; set; }
public DateTimeOffset DateTimeWithTz { get; set; }
public string GimmeJson()
{
return JsonConvert.SerializeObject(this);
}
}
public void SerializeDateThingy(int fraction)
{
var d = new MyDateHoldingThingy
{
DateTime = new DateTime(2017, 4, 3, 19, 21, 0, fraction),
DateTimeWithTz = new DateTimeOffset(2017, 4, 3, 19, 21, 0, fraction, TimeSpan.FromHours(2))
};
Console.WriteLine(d.GimmeJson());
}
Calling with
SerializeDateThingy(0);
SerializeDateThingy(999);
Result
{"DateTime":"2017-04-03T19:21:00","DateTimeWithTz":"2017-04-03T19:21:00+02:00"}
{"DateTime":"2017-04-03T19:21:00.999","DateTimeWithTz":"2017-04-03T19:21:00.999+02:00"}
If using Newtonsoft JSON directly, I can pass
new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fff" }
... which gives me desired consistency. I'm trying to fix output in our solution, which is mixture of WCF/ASP.NET+OData and I don't even know whether serialization happens via Json.net and not via .NET serializer (but that would most probably produced Date(...)
value) - still need to investigate more, however I didn't see any direct reference to Json.net.
Please note that I'm not doing serialization myself! This is covered by OData when dealing with output. I have actually no power to call serializer directly in my case. Code above is just example showing output inconsistency, which is seemingly default behavior.
So far, questions are:
- How do I set custom
IsoDateTimeConverter
globally (if Json.net is used)? - How do I set custom format to .NET (JSON and XML) serializers?
- Could anyone point me to RFC where it says that if second fraction equals to 0, it's completely omitted?