Note that there are some explanatory texts on larger screens.

plurals
  1. POPrevent Json.NET 4.5 from appending timezone offset when using MicrosoftDateFormat
    text
    copied!<p>Short of a custom <code>DateTimeConverterBase</code> implementation, is there some way to keep Json.NET 4.5+, when set to use <code>DateFormatHandling.MicrosoftDateFormat</code>, from appending a timezone offset for any non-UTC <code>DateTime</code> it is given?</p> <pre><code>"\/Date(1333645844276-0600)\/" </code></pre> <h2>Details</h2> <p>I am switching an API project from using the built-in .NET <code>JavaScriptSerializer</code> to using Json.NET to generate JSON. In Json.NET, for a UTC <code>DateTime</code>, the default datetime serialization was similar to the .NET version:</p> <pre><code>"\/Date(1333645844276)\/" </code></pre> <p>For non-UTC, unlike <code>JavaScriptSerializer</code>, Json.NET appends a timezone offset to the results (-6 for my area, this time of year):</p> <pre><code>"\/Date(1333645844276-0600)\/" </code></pre> <p>Here is the code I am using to switch Json.NET 4.5+ back to the <code>\/Date(...)\/</code> format (called <code>MicrosoftDateFormat</code>):</p> <pre><code>JsonSerializerSettings customJsonSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }; string result = JsonConvert.SerializeObject(DateTime.Now, customJsonSettings); </code></pre> <p>The solution seemed like it would be as simple as telling Json.NET to use a different <code>DateTimeZoneHandling</code> setting. I have tried every setting for <code>DateTimeZoneHandling</code> (<code>Local</code>, <code>Utc</code>, <code>Unspecified</code>, and <code>RoundtripKind</code>) and they all maintain the "-0600" in the output. In fact, they all produce identical results for a non-UTC <code>DateTime</code>.</p> <pre><code>JsonSerializerSettings customJsonSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc }; string result = JsonConvert.SerializeObject(DateTime.Now, customJsonSettings); "\/Date(1333647855743-0600)\/" </code></pre> <h2>Caveat</h2> <p>Ideally, I would have all my times in UTC already. I certainly plan to do so with the next version of this API. Since this is a live API, it is not worth risking an output change until a new version is released. It doesn't appear to be an issue for most JSON parsing systems, but I cannot risk the change since the JSON standard doesn't officially say anything about date serialization.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload