1

I have the following json coming back for a serialized date property:

/Date(1392508800000+0000)/

Can anyone tell me how I can get a javascript date out of this?

1 Answer 1

4
if (!Date.parseJSON) {
    Date.parseJSON = function (date) {
        if (!date) return "";
        return new Date(parseFloat(date.replace(/^\/Date\((\d+)\)\/$/, "$1")));
    };
}

then

var myVar = Date.parseJSON("/Date(1392508800000+0000)/")

Edit

I created a function that will recursively cycle through a returned JSON object and fix any dates. (Unfortunately it does have a dependency on jQuery), but here it is:

// Looks through the entire object and fix any date string matching /Date(....)/
function fixJsonDate(obj) {
    var o;
    if ($.type(obj) === "object") {
        o = $.extend({}, obj);
    } else if ($.type(obj) === "array") {
        o = $.extend([], obj);
    } else return obj;


    $.each(obj, function (k, v) {

        if ($.type(v) === "object" || $.type(v) === "array") {
            o[k] = fixJsonDate(v);
        } else {
            if($.type(v) === "string" && v.match(/^\/Date\(\d+\)\/$/)) {
                o[k] = Date.parseJSON(v);
            }
            // else don't touch it
        }
    });
    return o;
}

And then you use it like this:

// get the JSON string
var json = JSON.parse(jsonString);
json = fixJsonDate(json);
Sign up to request clarification or add additional context in comments.

1 Comment

This actually works nicely to replace all dates through out a JSON string /\/Date((\d+)(?:[-\+]\d+)?)\//i;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.