ASP.Net and JSON date/time strings

by Charles Cherry

This has bit me a couple of times now, so I am posting this here for my own future reference.

FROM an MSDN article :

ASP.NET AJAX: Inside JSON date and time string

The AJAX JSON serializer in ASP.NET encodes a DateTime instance as a JSON string. During its pre-release cycles, ASP.NET AJAX used the format “@ticks@“, where ticks represents the number of milliseconds since January 1, 1970 in Universal Coordinated Time (UTC). A date and time in UTC like November 29, 1989, 4:55:30 AM would be written out as “@62831853071@.” Although simple and straightforward, this format cannot differentiate between a serialized date and time value and a string that looks like a serialized date but is not meant to be deserialized as one. Consequently, the ASP.NET AJAX team made a change for the final release to address this problem by adopting the “\/Date(ticks)\/” format.

The new format relies on a small trick to reduce the chance for misinterpretation. In JSON, a forward-slash (/) character in a string can be escaped with a backslash (\) even though it is not strictly required. Taking advantage of this, the ASP.NET AJAX team modified JavaScriptSerializer to write a DateTime instance as the string “\/Date(ticks)\/” instead. The escaping of the two forward-slashes is superficial, but significant to JavaScriptSerializer. By JSON rules, "\/Date(ticks)\/" is technically equivalent to "/Date(ticks)/" but the JavaScriptSerializer will deserialize the former as a DateTime and the latter as a String. The chances for ambiguity are therefore considerably less when compared to the simpler “@ticks@” format from the pre-releases.

Here is how to deserialize the ASP.Net datetime string on the client-side:

function DateDeserialize(dateStr) {
return eval('new' + dateStr.replace(/\//g, ' '));