JavaScriptSerializer UTC DateTime issues

JavaScriptSerializer, and DataContractJsonSerializer are riddled with bugs. Use json.net instead. Even Microsoft has made this switch in ASP.Net MVC4 and other recent projects.

The /Date(286769410010)/ format is proprietary and made up by Microsoft. It has problems, and is not widely supported. You should use the 1979-02-02T02:10:10Z format everywhere. This is defined in ISO8601 and RF3339. It is both machine and human readable, lexically sortable, culture invariant, and unambiguous.

In JavaScript, if you can guarantee you will be running on newer browsers, then use:

date.toISOString()

Reference here.

If you want full cross-browser and older-browser support, use moment.js instead.

UPDATE

As an aside, if you really want to keep using JavaScriptSerializer, you could deserialize to a DateTimeOffset, which would preserve the correct time. You could then get the UTC DateTime from there, as follows:

// note, you were missing the milliseconds in your example, I added them here.
s = "\"1979-02-02T02:10:10.010Z\"";

dateActual = js.Deserialize<DateTimeOffset>(s).UtcDateTime;

Your test will now pass.

Leave a Comment