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?

user229044
  • 232,980
  • 40
  • 330
  • 338
dagda1
  • 26,856
  • 59
  • 237
  • 450

1 Answers1

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);
paulslater19
  • 5,869
  • 1
  • 28
  • 25
  • 1
    This actually works nicely to replace all dates through out a JSON string /\/Date\((\d+)(?:[-\+]\d+)?\)\//i; – dagda1 Feb 16 '12 at 13:49