我正在尝试将JSON字符串日期(在Google Apps脚本中)转换为JavaScript日期对象,然后检查该日期是否在另一个日期之后,但是我无法使其正常工作。
我尝试使用建议here。但我的输出不正确。我究竟做错了什么?谢谢你的帮助。
代码段:
var json = JSON.parse(resp);
var flightDate = new Date(json[i].flightDate)
for (i = 0; i < json.length; i++ {
flightDate = json[i].flightDate
traveler = json[i].traveler
flight = json[i].flight
destination = json[i].destination
var afterDate = new Date('1997-07-30')
if (flightDate >= afterDate) {
output.push ([flightDate, traveler, flight, destination])
}
}
输出:
1969-12-31
JSON:
[{"flightDate": "2013-03-01",
"traveler": "Paul Carter",
"flight": "JetBlue",
"destination": "Australia"
},
{"flightDate": "1997-02-18",
"traveler": "Paul Carter",
"flight": "American Airlines",
"destination": "Australia"
},
{"flightDate": "2004-05-25",
"traveler": "Paul Carter",
"flight": "JetBlue",
"destination": "Chile"
},
{"flightDate": "1995-08-05",
"traveler": "Paul Carter",
"flight": "United",
"destination": "Ireland"
}]
更新:
此问题中的JSON已更新,以准确反映我在计算机上拥有的内容,因此问题不是JSON格式。我主要对将JSON字符串日期转换为JavaScript日期感兴趣。请注意,由于这是在Google Apps脚本中,因此无法导入库(即Moment.js)。
最佳答案
首先,如果这是json的副本,则解析将无法进行,因为其中缺少,
。
更正json之后,您可以使用Arrays过滤器来获取特定日期之后的航班。
var data = [{
flightDate: "2013-03-01",
traveler: "Paul Carter",
flight: "JetBlue",
destination: "Australia"
}, {
flightDate: "1997-02-18",
traveler: "Paul Carter",
flight: "American Airlines",
destination: "Australia"
}, {
flightDate: "2004-05-25",
traveler: "Paul Carter",
flight: "JetBlue",
destination: "Chile"
}, {
flightDate: "1995-08-05",
traveler: "Paul Carter",
flight: "United",
destination: "Ireland"
}];
var afterDate = new Date("2000-01-01");
var flightsAfter = data.filter(function(flight) {
return new Date(flight.flightDate) >= afterDate;
});
console.log(flightsAfter);
关于javascript - 将JSON字符串日期转换为JavaScript(Google Apps脚本),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39665330/