我已经被困在这几天,JavaScript中的日期非常令人困惑。 我需要迭代一些JSON并过滤不到2小时且超过2个月的对象。
这是JSON的一个例子:
[
{
"Email":"example@email.com",
"TimeSlotsDate":"2017-01-28",
"TimeSlotsAvailable":[
{
"start":"11:00",
"end":"12:00"
},
{
"start":"12:00",
"end":"13:00"
},
{
"start":"13:00",
"end":"14:00"
},
{
"start":"15:00",
"end":"16:00"
},
{
"start":"16:00",
"end":"17:00"
},
{
"start":"17:00",
"end":"18:00"
}
],
},
{
"Email":"example@email.com",
"TimeSlotsDate":"2017-02-01",
"TimeSlotsAvailable":[
{
"start":"12:00",
"end":"13:00"
},
{
"start":"13:00",
"end":"14:00"
},
{
"start":"14:00",
"end":"15:00"
},
{
"start":"15:00",
"end":"16:00"
},
{
"start":"16:00",
"end":"17:00"
},
{
"start":"17:00",
"end":"18:00"
}
],
}]
我编写了一个可以从JSON创建可用日期的函数,但是我被困在我从TimeSlotsAvailable
数组中删除对象的部分,这些对象提前不到2小时,提前超过2个月。
这是功能:
var filterTimeslots = function (_timeSlots) {
var result = [];
var currentDate = new Date();
var timeZoneOffset = currentDate.getTimezoneOffset() / 60;
for (var i in _timeSlots) {
var day = _timeSlots[i].TimeSlotsDate.substring(8, 10);
var month = _timeSlots[i].TimeSlotsDate.substring(5, 7);
var year = _timeSlots[i].TimeSlotsDate.substring(0, 4);
for (var x in _timeSlots[i].TimeSlotsAvailable) {
var timeSlotStrt = _timeSlots[i].TimeSlotsAvailable[x].start.substring(0, 2);
var timeZoneTime = parseInt(timeSlotStrt) - timeZoneOffset;
var timeSlotDate = new Date(year, month, day, timeZoneTime);
if (timeSlotDate < currentDate) {
//the timeslot is less than 2 hours away
}
if (timeSlotDate > currentDate) {
//the timeslot is more than 2 months ahead
}
return result;
}
}
};
该函数应返回一个排除无效时隙的过滤数组。
非常感谢任何帮助。
答案 0 :(得分:0)
使用时刻应该很容易
var arr = [{
"Email": "example@email.com",
"TimeSlotsDate": "2016-08-16",
"TimeSlotsAvailable": [{
"start": "17:00",
"end": "18:00"
}],
}, {
"Email": "example@email.com",
"TimeSlotsDate": "2017-02-08",
"TimeSlotsAvailable": [{
"start": "11:00",
"end": "12:00"
}, {
"start": "12:00",
"end": "13:00"
}, {
"start": "13:00",
"end": "14:00"
}, {
"start": "15:00",
"end": "16:00"
}, {
"start": "16:00",
"end": "17:00"
}, {
"start": "17:00",
"end": "18:00"
}],
}, {
"Email": "example@email.com",
"TimeSlotsDate": "2017-02-01",
"TimeSlotsAvailable": [{
"start": "12:00",
"end": "13:00"
}, {
"start": "13:00",
"end": "14:00"
}, {
"start": "14:00",
"end": "15:00"
}, {
"start": "15:00",
"end": "16:00"
}, {
"start": "16:00",
"end": "17:00"
}, {
"start": "17:00",
"end": "18:00"
}],
}];
var now = moment();
var start = now.clone().add(2, 'hours');
var end = now.clone().add(2, "months");
console.log("NOW: ",now);
console.log("START: ",start);
console.log("END: ",end);
var res = arr.filter(function(el) {
return el.TimeSlotsAvailable.filter(function(subEl) {
var c = moment(el.TimeSlotsDate + " " + subEl.start);
return c >= start && c <= end;
}).length == el.TimeSlotsAvailable.length;
});
console.log(res.length, res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>