I’m trying to find week days between first date and second date (exclusive first and second). In the array that contains the weekday dates, the values get increment after line 1 in executed, which is unexpected.
private getListOfWeekDaysBetweenTwoDates(
startDate: Date,
endDate: Date
): Date[] {
const weekdaysList = [];
let tempDate = this.addDaystoGivenDate(startDate, 1);
while (tempDate < endDate) {
if (this.isWeekDay(tempDate)) {
weekdaysList.push(tempDate);
}
//line 1
tempDate = this.addDaystoGivenDate(tempDate, 1);
}
return weekdaysList;
}
private addDaystoGivenDate(date: Date, numberOfDays: number): Date {
return new Date(date.setUTCDate(date.getUTCDate() + numberOfDays));
}
private isWeekDay(day: Date): boolean {
if (day.getUTCDay() >= 1 && day.getUTCDay() <= 5) {
return true;
}
return false;
}
How do I stop array values changing?
>Solution :
Isolating the problem, you’re changing the date after inserting it to the array, but what you’re inserting is a reference to the date:
let d = new Date()
d.setUTCDate(1)
const arr = []
arr.push(d)
console.log(arr)
d.setUTCDate(10)
console.log(arr) //date in arr changes from 1 to 10
That’s because you’re calling date.setUTCDate() over tempDate.
There is more than one way to solve it, but for example you could store not the reference to tempDate but a completely new Date object:
weekdaysList.push(tempDate); => weekdaysList.push(new Date(tempDate));
In the simplified example:
let d = new Date()
const arr = []
d.setUTCDate(1)
arr.push(new Date(d))
console.log(arr)
d.setUTCDate(10)
console.log(arr) //date in arr keeps 1