Friday 13 July 2012

Deserializing ASP.NET AJAX JSON date using JavaScript

Modern websites are using AJAX a lot to improve customer experience by redudcing/avoiding full page reload in response to a user interaction. When AJAX is used with ASP.NET DateTime values are deserialized into below format.

"\/Date(1342137600000)\/"

Following JavaScript function can be used to deserialize it into a JavaScript Date object.

function GetDateFromJSONString(s) {
                    var d = s.replace(/\/Date\(/gi, '');
                    d = d.replace(/\)\//gi, '');
                    return  new Date(Number(d));
}

var s = "\/Date(1342137600000)\/";

alert(GetDateFromJSONString(s));

The issue with this is that JavaScript will apply the locale timezone of the client's machine while doing the deserialization which may result in a different Date value. This can be avoided by doing the deserialization bit differrently using JavaScript's toUTCString() method. This function will deserialize it into UTC Date.

var monthNames = { JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, 
JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11 }

function GetUTCDateFromJSONString(s) {
         var d = s.replace(/\/Date\(/gi, '');
         d = d.replace(/\)\//gi, '');
         var utc = new Date(Number(d)).toUTCString(); 
         //Sample value: Mon, 1 Feb 1982 00:00:00 UTC
         utc = utc.split(',')[1].substring(1).split(' ');
         utc[0] = utc[3] != '00:00:00' ? Number(utc[0]) + 1 : utc[0]; 
         return new Date(utc[2], monthNames[utc[1].toUpperCase()], utc[0]);  
}

var s = "\/Date(1342137600000)\/";

alert(GetUTCDateFromJSONString(s));



You can read more about toUTCString() method on w3schools.com. Click Here

No comments:

Post a Comment