Help

Re: Dates change after I push them onto a stack

Solved
Jump to Solution
1379 0
cancel
Showing results for 
Search instead for 
Did you mean: 
Peter_Borg
6 - Interface Innovator
6 - Interface Innovator

I’m having trouble writing a script that creates new records (representing jobs) based on the following parameters:

  • start of date range
  • end of date range
  • days(s) included
    That is, if Mondays are included, create a job on each monday within date range.

I use a function to add jobs onto a stack, and call the function for each day of the week as required. My stack is defined outside the function as:

Let newJobs = ;

The new records created included a date field. That’s the problem. I can see my function looping through the dates correctly, and even pushing them onto the stack. But when everything is finish, every job on my stack has the final loop date. The same date. It was updated even after being added to the stack!

Function is:

function addJobs(opp,start, end, offset) {
    let jobDate = new Date;
    if (offset >= start.getDay()) {
        let addDays = offset-start.getDay(); 
        jobDate.setDate(start.getDate()+addDays);
    }
    else {
        let addDays = 7+offset-start.getDay();
        jobDate.setDate(start.getDate()+addDays);
    }
    for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {        
        newJobs.push({
            "oppLink": opp,
            "newJobDate": current
        });
       )
    }
}

Greatful if anyone can point out where I’m going wrong please, and/or point me to a sample doing the same sort of thing.

1 Solution

Accepted Solutions
LukaszWiktor
6 - Interface Innovator
6 - Interface Innovator

It’s because date is mutable. You’re modifying the same object (current) and assigning it to each job. You’d need to clone the current date when adding it to newJobs.

for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {        
    newJobs.push({
        "oppLink": opp,
        "newJobDate": new Date(current.getTime())
    });
}

See Solution in Thread

4 Replies 4
LukaszWiktor
6 - Interface Innovator
6 - Interface Innovator

It’s because date is mutable. You’re modifying the same object (current) and assigning it to each job. You’d need to clone the current date when adding it to newJobs.

for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {        
    newJobs.push({
        "oppLink": opp,
        "newJobDate": new Date(current.getTime())
    });
}
Peter_Borg
6 - Interface Innovator
6 - Interface Innovator

Thanks @LukaszWiktor. Mutable – an important concept to know.

Hi @LukaszWiktor. 3 years later and this advice helped me 🙂 Very much appreciated

@Ricardo_da_Cost glad to know that my response what useful more than once. 😊