How to parse JSON to receive a Date object in JavaScript?

The JSON.parse function accepts an optional DateTime reviver function. You can use a function like this:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.

Leave a Comment