我们说我有一个像这样的JSON文件
[
{
"programId": "bla-bla-1",
"programTitle": "bla bla 1",
"programImg": "bla1.jpg",
"startsAt": "Apr 05 2017 11:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 12:00:00 GMT+0200 (EET)"
},
{
"programId": "bla-bla-2",
"programTitle": "bla bla 2",
"programImg": "bla2.jpg",
"startsAt": "Apr 05 2017 12:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 14:00:00 GMT+0200 (EET)"
},
{
"programId": "bla-bla-3",
"programTitle": "bla bla 3",
"programImg": "bla3.jpg",
"startsAt": "Apr 05 2017 14:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 16:00:00 GMT+0200 (EET)"
}
]
当前时间是(2017年4月05日 12:30:00 GMT + 0200(EET))如何使用Javascript从这些时间范围中获取当前程序我也可以使用像momentJS这样的库
答案 0 :(得分:1)
您可以这样做:
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})

答案 1 :(得分:1)
请注意,Tisus提供的解决方案可能无法在每个浏览器上运行,因为非标准字符串的日期解析与系统有关。
我建议使用moment(String, String)
而不是new Date(String)
来解析您的输入。然后,您可以使用时刻isBetween
来检查当前日期是否在给定范围内。
这是一个实时样本:
var input = [
{
"programId": "bla-bla-1",
"programTitle": "bla bla 1",
"programImg": "bla1.jpg",
"startsAt": "Apr 05 2017 11:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 12:00:00 GMT+0200 (EET)"
},
{
"programId": "bla-bla-2",
"programTitle": "bla bla 2",
"programImg": "bla2.jpg",
"startsAt": "Apr 05 2017 12:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 14:00:00 GMT+0200 (EET)"
},
{
"programId": "bla-bla-3",
"programTitle": "bla bla 3",
"programImg": "bla3.jpg",
"startsAt": "Apr 05 2017 14:00:00 GMT+0200 (EET)",
"endsAt": "Apr 05 2017 16:00:00 GMT+0200 (EET)"
}
]
var prog = input.find(item => {
//var now = moment();
// mocking current time in order to get always the same result
var now = moment("Apr 05 2017 12:30:00 GMT+0200 (EET)", 'MMM DD YYYY HH:mm:ss Z')
var start = moment(item.startsAt, 'MMM DD YYYY HH:mm:ss Z');
var end = moment(item.endsAt, 'MMM DD YYYY HH:mm:ss Z');
return now.isBetween(start, end);
});
console.log(prog);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
旁注:我同意Rajesh,提供代码尝试有助于获得更好的答案,并让您有机会更好地学习。