Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Json日期字符串转换为JavaScript日期对象_Javascript_Regex_Json - Fatal编程技术网

将Json日期字符串转换为JavaScript日期对象

将Json日期字符串转换为JavaScript日期对象,javascript,regex,json,Javascript,Regex,Json,我有以下JSON对象,该对象具有以下格式的日期字段: { "AlertDate": "\/Date(1277334000000+0100)\/", "Progress": 1, "ReviewPeriod": 12 } 我想编写一个正则表达式或一个函数,将其转换为javascript对象,使其形式如下: { "AlertDate": new Date(1277334000000), "Progress": 1, "ReviewPeriod":

我有以下JSON对象,该对象具有以下格式的日期字段:

{
    "AlertDate": "\/Date(1277334000000+0100)\/",
    "Progress": 1,
    "ReviewPeriod": 12 
}
我想编写一个正则表达式或一个函数,将其转换为javascript对象,使其形式如下:

{
    "AlertDate": new Date(1277334000000),
    "Progress": 1,
    "ReviewPeriod": 12 
}
上述日期格式在JQuery parseJSON方法中验证失败

我想将1277334000000+0100转换为正确的毫秒数,以便在验证后调用eval时创建正确的日期


有谁能帮我找到解决这个问题的好方法吗?

除非你真的需要,否则你真的不应该使用eval;为什么不直接在JSON中输入秒数,并在需要格式化时调用该数字的日期


如果必须,可以使用正则表达式从字符串中解析出数字,这就是您要查找的吗

如果这是对象中的一项: o={ “警报日期”:“/日期(1277334000000+0100)/”, "进展":一,, “审查期”:12 }

此代码将提取第一个值数字(忽略“+0100”),转换为数字并创建日期对象

var rxFirstNumber = /(\d+)/;
var strAlertDate = o.AlertDate;
var arrMatches,intTimeStamp;

arrMatches = strAlertDate.match(rxFirstNumber);
if (arrMatches !== null && arrMatches.length > 0) {
    intTimeStamp = parseInt(arrMatches[1],10);
    o.AlertDate = new Date(intTimeStamp);
}
如果您可以相信您的数据始终包含该字符串数据(或者至少该AlertDate始终是一个包含数字的字符串),则可以用一行(讨厌且无法维护的)代码表示:


我需要一个更全面的答案,而不仅仅是改变一个单独财产的日期

我需要更改JSON字符串中的所有日期,而不仅仅是一个属性

我最终得到了以下正则表达式

data = data.replace(new RegExp('\\"\\\\\/Date\\((\\d{13}\\+\\d{4})\\)\\\\\/\\"', 'g'), "new Date($1)");
自动解析日期的可重用jQuery扩展 我已经编写了一个jQuery扩展(如果您确实使用了,我希望/建议您这样做),它可以更改$.parseJSON()功能,以便能够为您自动解析日期。不再需要重复的日期解析代码


检查代码。

您好,我只想添加到BalusC答案:

如果您希望某些较旧日期的日期不被取消定义,而不是

json.AlertDate = new Date(parseInt(json.AlertDate.replace(/(^.*\()|([+-].*$)/g, '')));
你可以:

var dateObject = new Date(new Number(yourDateVariable.replace(/(^.*\()|([+-].*$)/g, '')));
我想你写了两次“AlertDate”:。
var dateObject = new Date(new Number(yourDateVariable.replace(/(^.*\()|([+-].*$)/g, '')));