Friday, August 12, 2011


Although JSON is a great and simple format, I’m not a big fan of the way dates are represented.  If you have a look at a JSONResult in ASP.NET MVC you’ll probably see some data like this:


You’ll see that the Date is:


Not very JavaScript friendly. We tried a lot of different approaches in getting something more useful back from our action results(including just using strings instead of datetimes). In the end we decided to use the  jQuery’s dataFilter property. The dataFilter function is used to sanitize a response from a web server.  We ended up with the following small jQuery code:

$.ajaxSettings.dataFilter = function (data, type) {
if (type === 'json') {
data = data.replace(/\/Date\((.*?)\)\//gi,
function (fullMatch, $1, $2, $3) {
try {
return $1 + new Date(parseInt($2.substr(6))).toUTCString() + $3;
catch (e) { }
return $1 + $2 + $3;
return data;

This method uses a regular expression to look for the various elements that represent a Date in Microsoft JSON serialization format. The resulting date is reformatted to a human readable string. This format can be understood by other JavaScript components like for example the jQuery jqGrid.

Anyone with a better alternative?

1 comment:

Anonymous said...