Deserializing Client-Side AJAX JSON Dates

Question!

Given the following JSON Date representation:

"\/Date(1221644506800-0700)\/"

How do you deserialize this into it's JavaScript Date-type form?

I've tried using MS AJAX JavaScrioptSerializer as shown below:

Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/")

However, all I get back is the literal string date.



Answers

For those who don't want to use Microsoft Ajax, simply add a prototype function to the string class.

E.g.

    String.prototype.dateFromJSON = function () {
    return eval(this.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
};

Don't want to use eval? Try something simple like

var date = new Date(parseInt(jsonDate.substr(6)));

As a side note, I used to think Microsoft was misleading by using this format. However, the JSON specification is not very clear when it comes to defining a way to describe dates in JSON.



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.
By : ESV


Provided you know the string is definitely a date I prefer to do this :

 new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))


This video can help you solving your question :)
By: admin