Deserializing Client-Side AJAX JSON Dates
Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, described the design of the JavaScriptSerializer DateTime output and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation:
run a simple search for "\/Date((\d+))\/" and replace with "new Date($1)" before the eval (but after validation)
I implemented that as:
var serializedDateTime = "\/Date(1271389496563)\/";document.writeln("Serialized: " + serializedDateTime + "<br />");var toDateRe = new RegExp("^/Date\\((\\d+)\\)/$");function toDate(s) { if (!s) { return null; } var constructor = s.replace(toDateRe, "new Date($1)"); if (constructor == s) { throw 'Invalid serialized DateTime value: "' + s + '"'; } return eval(constructor);}document.writeln("Deserialized: " + toDate(serializedDateTime) + "<br />");
This is very close to the many of the other answers:
- Use an anchored RegEx as Sjoerd Visscher did -- don't forget the ^ and $.
- Avoid string.replace, and the 'g' or 'i' options on your RegEx. "/Date(1271389496563)//Date(1271389496563)/" shouldn't work at all.
A JSON value is a string, number, object, array, true, false or null. So this is just a string. There is no official way to represent dates in JSON. This syntax is from the asp.net ajax implementation. Others use the ISO 8601 format.
You can parse it like this:
var s = "\/Date(1221644506800-0700)\/";var m = s.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);var date = null;if (m) date = new Date(1*m[1] + 3600000*m[2] + 60000*m[3]);