转换.NET日期格式转换为JavaScript日期
问题描述:
我有以下的JSON回来序列化的日期属性:转换.NET日期格式转换为JavaScript日期
/日期(1392508800000 + 0000)/
谁能告诉我怎样才能得到一个javascript约会呢?
答
if (!Date.parseJSON) {
Date.parseJSON = function (date) {
if (!date) return "";
return new Date(parseFloat(date.replace(/^\/Date\((\d+)\)\/$/, "$1")));
};
}
然后
var myVar = Date.parseJSON("/Date(1392508800000+0000)/")
编辑
我创建了一个将通过返回的JSON对象递归循环,修复任何日期的功能。 (遗憾的是它确实有jQuery的依赖),但在这里它是:
// 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;
}
然后你使用这样的:
// get the JSON string
var json = JSON.parse(jsonString);
json = fixJsonDate(json);
其实,这很好地工作,通过了一个JSON字符串替换所有日期/ \ /日期\((\ d +)(:?[ - \ +] \ d +)\)\ // I; – dagda1 2012-02-16 13:49:15