我从API获取了一系列日期:
0:{date: "2016-11-17T00:00:00",…}
1:{date: "2016-11-18T00:00:00",…}
2:{date: "2016-11-19T00:00:00",…}
3:{date: "2016-11-21T00:00:00",…}
4:{date: "2016-11-22T00:00:00",…}
5:{date: "2016-11-23T00:00:00",…}
在此示例中,数组缺少此日期:
{date: "2016-11-20T00:00:00",…}
从Javascript或Angular中的日期数组中找到丢失的一天的最佳方法是什么?
因此我以后可以将它作为禁用日传递给日期选择器。
答案 0 :(得分:1)
创建一个新数组missingDates []
使用for循环
迭代数组(来自您的API)for (i = 0; i < array.length; i++){
var date1 = convert your array item (with index i) to a date
var date2 = convert your array item (with index i + 1) to a date (keep in mind, index i + 1 cant be > than array.length)
//calculate diffDays between the 2 dates, if diff is > 1, you have a missing date
var missingDate = create your missing date (use your date1 variable + 1Day)
//add misingDate to missingDates[] array
missingDates.push(missingDate)
}
答案 1 :(得分:1)
检查出来:
首先,您可以使用Array.prototype.sort
然后使用Array.prototype.reduce
和hash table
查找缺少的日期
以下代码段中的演示:
var array=[
{date:"2016-11-17T00:00:00"},
{date:"2016-11-19T00:00:00"},
{date:"2016-11-18T00:00:00"},
{date:"2016-11-21T00:00:00"},
{date:"2016-11-22T00:00:00"},
{date:"2016-11-23T00:00:00"},
{date:"2016-11-27T00:00:00"}
];
var result = array.sort(function(a,b){
return Date.parse(a.date) - Date.parse(b.date);
}).reduce(function(hash){
return function(p,c){
var missingDaysNo = (Date.parse(c.date) - hash.prev) / (1000 * 3600 * 24);
if(hash.prev && missingDaysNo > 1) {
for(var i=1;i<missingDaysNo;i++)
p.push(new Date(hash.prev+i*(1000 * 3600 * 24)));
}
hash.prev = Date.parse(c.date);
return p;
};
}(Object.create(null)),[]);
console.log(result);
&#13;
.as-console-wrapper{top:0;max-height:100%!important;}
&#13;
答案 2 :(得分:1)
如果没有缺少日期,您可以执行方法getMissingDate
返回null
,如果大于一天的日期之间存在差异,则可以返回Date
对象:
var arr1 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
arr2 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-20T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
getMissingDate = function(arr) {
var result = null;
for (var i = 0, l = arr.length - 1; i < l; i++) {
var current = new Date(arr[i].date),
next = new Date(arr[i + 1].date);
if (1 < Math.ceil(Math.abs(next.getTime() - current.getTime()) / (1000 * 3600 * 24))) {
result = new Date(current.setDate(current.getDate() + 1));
break;
}
}
return result;
};
console.log('arr1:', getMissingDate(arr1));
console.log('arr2:', getMissingDate(arr2));
&#13;