0

I have created an array of dates for the last year and I need to find the index in the array of a given date but it returns -1

However if I hardcode dates which isn't nice as it's not dynamic, it works and outputs 331 which is what I expect

What can I do to get this to work?

// 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

This 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); // dumps 331
Andy G
  • 19,232
  • 5
  • 47
  • 69
Peter Griffin
  • 300
  • 5
  • 18

1 Answers1

2

Because you are not setting hours, minutes onwards to 0, so new Date() is taking current time-stamp which you need to clear.

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

Demo

// 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);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94