我已经为去年创建了一个日期数组,我需要在给定日期的数组中找到索引,但它返回-1
然而,如果我硬编码不好的日期,因为它不是动态的,它可以工作并输出331,这是我所期待的
我该怎么做才能让它发挥作用?
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
var today = new Date(),
last_year = new Date();
last_year.setMonth(last_year.getMonth() - 12);
last_year.setDate(last_year.getDate() + 1);
var dates = getDates(last_year, today);
var d = new Date(2017, 10, 31);
var test = dates.map(Number).indexOf(+d);
console.log(test); // dump -1
这有效.....
dates = getDates(new Date(2017, 0, 4), new Date(2018, 12, 4));
d = new Date(2017, 10, 31);
test = dates.map(Number).indexOf(+d);
console.log(test); // dumps 331
答案 0 :(得分:2)
由于您未将小时,分钟设置为0
,因此new Date()
正在当前时间戳你需要清除的。
last_year.setMonth(last_year.getMonth() - 12);
last_year.setDate(last_year.getDate() + 1);
last_year.setHours(0,0,0,0); //this line is added
<强>演示强>
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
var today = new Date(),
last_year = new Date();
last_year.setMonth(last_year.getMonth() - 12);
last_year.setDate(last_year.getDate() + 1);
last_year.setHours(0,0,0,0);
var dates = getDates(last_year, today);
var d = new Date(2017, 10, 31);
var test = dates.map(Number).indexOf(+d);
console.log(test);
// works
dates = getDates(new Date(2017, 0, 4), new Date(2018, 12, 4));
d = new Date(2017, 10, 31);
test = dates.map(Number).indexOf(+d);
console.log(test);
&#13;