小编典典

将json结果转换为日期

json

我从JavaScript进行$ getJSON调用得到以下结果。如何在JavaScript中将start属性转换为正确的日期?

[{“ id”:1,“ start”:“ / Date(1238540400000)/”},{“ id”:2,“ start”:“ /
Date(1238626800000)/”}]

谢谢!


阅读 312

收藏
2020-07-27

共1个答案

小编典典

您需要从字符串中提取数字,并将其传递给Date constructor

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

这些部分是:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
2020-07-27