Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing Client-Side AJAX JSON Dates

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.

like image 921
Brian Chavez Avatar asked Sep 17 '08 11:09

Brian Chavez


People also ask

How to give date value in JSON?

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).

Can JSON parse date?

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.

How do I format a Microsoft JSON date?

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.


2 Answers

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

 new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)) 
like image 70
Simon_Weaver Avatar answered Oct 02 '22 16:10

Simon_Weaver


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.
like image 43
ESV Avatar answered Oct 02 '22 15:10

ESV