Derserializing ASP.NET MVC JSON formatted Date strings

Have you called an Ajax based action in MVC, only to find that the Date format is being serialized into something that isn’t entirely useful on the client?

{“result”:[{“Author”:”Aaron”,”SentAt”:”\/Date(1296824894700)\/”,”Text”:”Blah Blah”,”Id”:1}],”runAt”:”\/Date(1297031297600)\/”}

You’ll see that the Date is:

\/Date(1296824894700)\/

Alas, that’s not very friendly. For a quick translation, I added the following to jQuery’s dataFilter property so that the date would be formatted in a more human readable format. The dataFilter function is used to sanitize a response from a web server.  Here’s what I added:

$(function () {
    $.ajaxSettings.dataFilter = function (data, type) {
        if (type === 'json') {
            // convert things that look like Dates into a UTC Date string
            // and completely replace them. 
            data = data.replace(/(.*?")(\\\/Date\([0-9\-]+\)\\\/)(")/g,
                function (fullMatch, $1, $2, $3) {
                    try {
                        return $1 + new Date(parseInt($2.substr(7))).toUTCString() + $3;
                    }
                    catch (e) {}
                    // something miserable happened, just return the original string            
                    return $1 + $2 + $3;
                });
        }
        return data;
    };
});

The trick for converting the /\Date(#)\/ syntax easily was from StackOverflow. It even handles time zone info.

I added 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. There are 3 capturing groups that I’ve named $1, $2, and $3 which need to be preserved otherwise the JSON string is mangled beyond recognition. Those are returned concatenated to preserve the original formatting of the string.

The resulting date is translated to something like:

Fri, 4 Feb 2011 13:08:14 UTC

Of course, you could do whatever formatting you’d like.

 

Bonus

And, as a bonus, you did notice that if you’re using IE9, that the developer tools now have a network trace? Cool. (I’ll still use fiddler for many things, but this will be very handy on machines that don’t have fiddler installed).

SNAGHTML51b4c85a