Thursday, February 12, 2009

Tip: Converting MS Ajax JSON DateTime to JS Date object

In my recent project, i have to use JSON Serialization to translate a datatable into JSON format. The table contains fields that are of DateTime data type. When the data is deserialized in the browser, the data is always represented in "/Date(1325926000000-0800)/".

I know i can use the the MS Ajax JS API "Sys.Serialization.JavaScriptSerializer.deserialize" to deserialize the data back into JS Date object but i dont want to include the immense MS JS script library into my page. So the option is to use the JS below to do the trick.

var dt    = data.updateDateTime; //assuming it's like /Date(1325926000000-0800)/
var s = eval(dt.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
dt = new Date(s);
var mil = Date.UTC(dt.getFullYear(),dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()); //Miliseconds since January 1, 1970
dt      = new Date(mil); //Convert to local time

No comments: