giant enemy spycrab
giant enemy spycrab

Reputation: 43

How do I populate a Javascript array with a series of dates from a loop?

Here's the code I'm working on:

    function populateDates() {
      var start = new Date(2017, 7, 13);
      var end = new Date(2017, 8, 3);
      var tempDate = start;
      var endPlus90 = end.setDate(end.getDate() + 90);
      var today = new Date();
      var array = [];
      for(var d = start; d < today || d < endPlus90; d.setDate(d.getDate() + 1)){
        if (d.getDay() !== 0 && d.getDay() !== 6){
          array.push([d]);
        }
      }
      return array;
    }
    var future = new Date();
    future.setDate(future.getDate() + 90);
    console.log(populateDates(new Date(), future));

Basically, what I'm trying to do is, given an arbitrary start and end date, generate a list of dates, excluding weekends, from the start date to either 90 days after the end date, or the current date, whichever is earlier. The current function generates an array that is all identical dates which are 90 days after the end date. I'm not very familiar with Javascript, so I'm not sure what's going wrong here. I suspect that the way I'm pushing the variable to the array is incorrect.

Upvotes: 3

Views: 212

Answers (2)

Austin Ezell
Austin Ezell

Reputation: 763

The problem comes with your usage of setDate which returns

The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

Wrap that setDate line in a new Date() and your code should run just fine.


As others pointed out the reason the array had multiples of the same date is because you were pushing references to the same single date object, and reassigning that object's date, which was updating it each of these references. By creating a new Date with new Date() you are creating a new object with its own reference.

Upvotes: 3

Jimenemex
Jimenemex

Reputation: 3186

Try this out. You need to initialize the d to a new Date every time. You can't just change the day. You also need to put new Date() around end.setDate(). setDate() returns milliseconds.

function populateDates(start, end) {
    var tempDate = start;
    var endPlus90 = new Date(end.setDate(end.getDate() + 90));
    var today = new Date();
    var array = [];
    for(var d = tempDate; d < endPlus90; d = new Date(d.setDate(d.getDate() + 1))){ 
      if(d >= today) { // Stop counting dates if we reach the current date
        break;
      } 
      if (d.getDay() !== 0 && d.getDay() !== 6){
        array.push([d]);
      }
    }
    return array;
}

var future = new Date(); // As of 10/18/2017
future.setDate(future.getDate() + 90);
console.log(populateDates(new Date(2017, 9, 1), future)); // Prints 13 days as of 10/18/2017   
console.log(populateDates(new Date(2016, 9, 1), future)); // Prints 273 days

Upvotes: 2

Related Questions