javascriptarraysdatepickadate

Subtracting 1 month from array of dates


The date picker I am using is zero indexed, it displays the "wrong date" by 1 month. So I need to correct for that. I am trying to build an array of dates in the following format and then correct for the bug in the date picker (subtract 1 month) and then insert it into the date picker. Here is the code that I have written so far but that only works with a string, not an array.

Example of what I want to do:

var array = [
        new Date("11/28/2019"),
        new Date("12/25/2019"),
        new Date("01/01/2020"),
        new Date("01/20/2020"),
        new Date("02/17/2020"),
        new Date("05/25/2020"),
        new Date("07/04/2020"),
        new Date("09/07/2020"),
        new Date("11/26/2020"),
        new Date("12/25/2020"),
        ];

fixeddates.setMonth(array.getMonth() - 1);

But I need fixeddates to output an array in this format: [yyyy, m, d]

So essentially I need to subtract 1 month to all those dates and change the format to the date picker accepted format.

Thanks!


Solution

  • You can "map" through the array to change each row into another object. In this case, I am converting each date to an array of (yyyy, mm, dd). Date.getMonth() already returns the value minus 1, so I didn't decrement it again.

    var array = [
            new Date("11/28/2019"),
            new Date("12/25/2019"),
            new Date("01/01/2020"),
            new Date("01/20/2020"),
            new Date("02/17/2020"),
            new Date("05/25/2020"),
            new Date("07/04/2020"),
            new Date("09/07/2020"),
            new Date("11/26/2020"),
            new Date("12/25/2020"),
            ];
    
    var fixedDates = array.map(function(date) {
      return [date.getFullYear(), date.getMonth(), date.getDate()]
    });
    console.log(fixedDates);