0

try below code

let startDate = new Date();
const lastDate = new Date();
lastDate.setMonth(11,31);

const timeArray = [];

while(startDate <lastDate){
  timeArray.push(startDate);
  console.log(startDate)
  startDate =new Date(startDate.setMonth(startDate.getMonth()+1)) 
}
console.log('==================================');
console.log(timeArray)

But result shows as below

Thu Nov 03 2022 09:12:03 GMT+0530 (India Standard Time)
Sat Dec 03 2022 09:12:03 GMT+0530 (India Standard Time)
==================================
[
Sat Dec 03 2022 09:12:03 GMT+0530 (India Standard Time)
Tue Jan 03 2023 09:12:03 GMT+0530 (India Standard Time)
]

When I console the 'startDate' just after the array push it shows as expected , But when I console log the time array it has been shifted . Can someone explain this?

Wyck
  • 10,311
  • 6
  • 39
  • 60
devaka dabare
  • 39
  • 1
  • 10
  • 1
    Well, you did call setMonth on the Date object. Perhaps you find it unexpected that it set the month of the Date object that you pushed into the array? – Wyck Nov 03 '22 at 04:06
  • try logging after > `startDate =new Date(startDate.setMonth(startDate.getMonth()+1))` You will get the point – ilyasbbu Nov 03 '22 at 04:10

1 Answers1

2

I believe below is the code you were intending to write, where you clone the startDate and then modify the clone instead of modifying the original.

let startDate = new Date();
const lastDate = new Date();
lastDate.setMonth(11,31);

const timeArray = [];

while(startDate <lastDate){
  timeArray.push(startDate);
  console.log(startDate)
  startDate = new Date(startDate); // uncouple it from the other date
  startDate.setMonth(startDate.getMonth()+1)
}
console.log('==================================');
console.log(timeArray)
Wyck
  • 10,311
  • 6
  • 39
  • 60