You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态生成年度日期数组查找指定日期返回-1的解决方法

解决日期数组查找索引返回-1的问题

遇到这种情况我太熟悉了!问题出在日期对象的时分秒差异上,咱们一步步拆解原因:

  • 你动态生成的last_year和today是基于当前运行代码的时间创建的,它们包含了具体的时分秒(比如你运行时的14:25:30)。
  • getDates函数里生成的每一个日期,都会继承初始日期的时分秒信息,导致数组里的所有日期都带有非0的时分秒。
  • 但你用来查找的d = new Date(2017, 10, 31)默认是当天的00:00:00,两者转成数字后的时间戳完全不一样,所以indexOf自然找不到匹配项,返回-1。
  • 硬编码起止日期时,new Date(2017, 0, 4)这种写法默认生成的是当天0点的日期,数组里的日期也都是0点,和d的时间戳一致,所以能正常找到索引331。

解决方案

咱们只需要确保所有参与对比的日期都是当天00:00:00的状态,有两种简单的实现方式:

方式一:修改getDates函数,统一清零时分秒

// 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);
        // 清零时分秒,确保是当天0点
        date.setHours(0, 0, 0, 0);
        return date;
    };
    // 先把起始和结束日期的时分秒也清零
    currentDate.setHours(0, 0, 0, 0);
    endDate.setHours(0, 0, 0, 0);
    while (currentDate <= endDate) {
        dates.push(currentDate);
        currentDate = addDays.call(currentDate, 1);
    }
    return dates;
};

方式二:在创建日期时单独清零时分秒

var today = new Date();
today.setHours(0, 0, 0, 0); // 清零当前日期的时分秒
var last_year = new Date(today);
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);
d.setHours(0, 0, 0, 0); // 确保查找的日期也是0点状态
var test = dates.map(Number).indexOf(+d);
console.log(test); // 现在就能返回正确的索引啦

顺便提个小细节:new Date(2018, 12, 4)其实是2019年1月4日,因为JavaScript的月份是从0开始计数的(0代表1月,11代表12月),不过这不是导致你问题的原因,只是个小知识点~

内容的提问来源于stack exchange,提问作者Peter Griffin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:02:54