Friday, April 15, 2011

Reading .NET JSON Date's in jQuery

ASP.Net writes out date objects to a JSON stream in the format { "\/Date(x)\/" } but jQuery will not automatically convert this to a JavaScript date but rather keeps it as a string. To fix that this simple converter script can be included in your global JavaScript header.

Note that this does requite jQuery 1.5+.

$.ajaxSetup({
    // Add a custom converter to convert ASP.NET JSON dates to JS Date object
    // That is convert { "\/Date(...)\/" } to { new Date(...) }
    converters: {
        "text json": function( textValue ) {
            return jQuery.parseJSON(textValue.replace(/"\\\/Date\((-?\d*)\)\\\/"/g, "new Date($1)"));
        }
    }
});

1 comment:

Vasili said...

How to use it ?!
I got same problem !
could you show me an example ?!

thank you.