dagda1
dagda1

Reputation: 28890

Convert .NET date format into JavaScript date

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?

Upvotes: 1

Views: 221

Answers (1)

paulslater19
paulslater19

Reputation: 5917

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);

Upvotes: 4

Related Questions