0

I am trying to create a range of dates in TypeScript. I used the code from here. This successfully adds a single increment for a month, but breaks down upon trying to add to the original value again, as it changes the values of both date and addedDate. How would I go about fixing this? Thanks.

const date = new Date("7 December 2023")
const durVal = 10;
for (let i = 0; i < Number(durVal) - 1; i++) {
  let addedDate = date;
  addedDate = new Date(addedDate.setMonth(addedDate.getMonth()+i));
  console.log(addedDate)
}

The output is: "2023-12-06T13:00:00.000Z", "2023-12-07T13:00:00.000Z", "2023-12-08T13:00:00.000Z"..."2026-12-06T13:00:00.000Z"

I would expect the code to increment the month upwards by 1 each time.

1 Answers1

0

Simply assigning let addedDate = date does NOT create a new date object instance. It makes addedDate reference to the original date variable. So if you modify addedDate, it will also change date variable coz they reference the same object.

function main(workbook: ExcelScript.Workbook) {
  // it is not a typo, `11` stands for Dec.
  const dateStart = new Date(2023, 11, 7); // Dec. 7, 2023, 
  const durVal = 4;
  // Option 1
  let addedDate = new Date(dateStart);
  // Option 2
  // let addedDate = new Date();
  // addedDate.setFullYear(dateStart.getFullYear(), dateStart.getMonth(), dateStart.getDate());
  console.log(dateStart.toDateString() + " <<START>> " + addedDate.toDateString());
  for (let i = 0; i < Number(durVal) - 1; i++) {
    addedDate.setMonth(addedDate.getMonth() + 1);
    console.log(dateStart.toDateString() + " <> " + addedDate.toDateString())
  }
}

enter image description here

taller_ExcelHome
  • 2,232
  • 1
  • 2
  • 12