我正在使用来自 Eventbrite API 的 JSON
响应来显示“下一个”事件巡演日期。该日期将通过查看当前时间并查找当前时间之后的下一个事件来自动计算。
这是我需要解析的 JSON
响应:
https://jsfiddle.net/dgc223/k9dbvzoo/
如果我现在检查它,我希望从第 277 行返回日期(2017-11-11T11:00:00)
。如果我在几个小时内查看,我会想返回第 350 行(2017-12-09T11:00:00)
,因为那是游览的下一个可用日期。
我当前的脚本(如下)从上面的 JSON
响应中返回该系列的第一个日期。但是,在考虑当前时间后,我需要对其进行修改以返回下一个巡演日期。这样,脚本可以通过告诉用户下一个可用的游览日期来提供更多信息。
<script>
$.getJSON('eventbrite_api2.php', {
eventid: '35719663475',
function: 'events'
}, function(response) {
var date = new Date(response.start.utc); //this formats the date to local
time zone
date.toString();
event_start = date.toLocaleString('en-US', {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: 'numeric',
hour12: true,
timeZone: "America/New_York"
}); //this formats the date to eastern time zone, and makes some other formatting of the date
var content = "<h4>" + response.name.text + "</h4><p>The next event starts " + event_start + "</p>" + "<p>" + "<img width=\"350\" src=" + response.logo.original.url + "</img>";
$("#eventbrite").append(content);
});
</script>
最佳答案
我会过滤掉所有已经过去的事件,然后使用第一个事件(如果有)。因此处理响应的函数将如下所示。
function (response) {
var date = new Date();
var upcoming = response.events.filter(function (event) {
// just compare the UTC representation
var start = new Date(event.start.utc);
return start > date;
});
if (upcoming.length) {
//next event is upcoming[0]; Do what you want with it
} else {
//no events upcoming
}
}
JavaScript 数组的过滤函数接受一个测试函数并返回一个新数组,其中仅包含第二个数组中在传递到测试函数时返回 true 的元素。
关于javascript - 从 JSON 响应输出下一个可用日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238460/