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.
There is no date format in JSON, there's only strings a de-/serializer decides to map to date values. However, JavaScript built-in JSON object and ISO8601 contains all the information to be understand by human and computer and does not relies on the beginning of the computer era (1970-1-1).
Use the toJSON() method to get a string representation of the Date object. Pass the JSON string to the Date() constructor. The Date() constructor will parse the ISO string and will create a Date object.
You can use this to get a date from JSON: var date = eval(jsonDate. replace(/\/Date\((\d+)\)\//gi, "new Date($1)")); And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.
Provided you know the string is definitely a date I prefer to do this :
new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With