0

I am writing a function to 'calculate' the dates of a working week based on the current date. Console.log of the array's item is correct in the cycle, but when I print the content of the array at the end of the cycle, all the items have the same value. I can't figure out what's wrong in my logic.

Any hing is much appreciated.

function calculateWorkingDays(){

    var weekDates = ["0","1","2","3","4","5","6"];
    var currentDate = new Date();
    var weekDay = currentDate.getDay();
    console.log("Initial weekDay: " +  weekDay);

    for (var i=0; i<7; i++){
        console.log(i);
        //check for Sunday (0)
        if (weekDay==0){
            weekDates[currentDate.getDay()] = currentDate;
            //console.log("if i=0: day" + currentDate.getDay());
            console.log("date: " + currentDate);
            console.log("day: " + currentDate.getDay());
            console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
            //set to Monday (1)
            weekDay = 1;
            currentDate.setDate(currentDate.getDate()-6);

        } else {
            if (weekDay<6) {
                weekDates[currentDate.getDay()] = currentDate;
                console.log("date: " + currentDate);
                console.log("day: " + currentDate.getDay());
                console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
                weekDay = weekDay + 1;
            } else {
                weekDates[currentDate.getDay()] = currentDate;
                console.log("date: " + currentDate);
                console.log("day: " + currentDate.getDay());
                console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
                // set to Sunday (0)
                weekDay = 0 ;
            }
            currentDate.setDate(currentDate.getDate()+1);
        }

    }

    console.log(weekDates.toString());


}
1
  • shouldnt you be incrementing something (possibliy weekDay) by i otherwise the code isnt changing on each run though? Commented Aug 7, 2015 at 13:21

1 Answer 1

3

The problem is that you fill weekDates array with the same content - DateTime object (stored in currentDate variable). And this incrementing line...

currentDate.setDate(currentDate.getDate()+1);

... doesn't assign a new object in currentDate - it augments the existing one instead.

The solution is: either clone or serialize this object (it depends on what you're going to do with it after).


As a sidenote, your approach can be simplified: instead of checking the dates inside the loop, just start the loop always from Monday. For example:

var currentDate = new Date();
var weekDay = currentDate.getDay();
if (weekDay === 0) {
  weekDay = 7;
}
currentDate.setDate(currentDate.getDate() - (weekDay - 1));

var weekDays = [currentDate];
var currentTimestamp = +currentDate;
var msInDay = 1000 * 24 * 60 * 60;
for (var i = 1; i < 7; i++) {
   weekDays.push(new Date(currentTimestamp + i * msInDay));
}
console.log(weekDays);

This code stores objects in an array; if that's not necessary, just serialize (with toString() or any other method fitting your needs) the stored DateTimes.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey Man, I am impressed.. not even the time to brush my teeth and here an answer already. I'll test you code tomorrow (but no doubt it will work!), but I don't quite understand you explanation of my error. currentDate increments it's value (+1 day) each iteration and the expression "console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]) " actually prints out the expected result .... again, quite hard to digest.
The key is understanding that in your current code you push the reference to the same object. When logging, you inspect this object right after modification, so it destined to show the correct result. But as each element of an array is the same object, when you inspect it afterwards it just shows the same dates.
I got it, it's a reference. I thought that I was copying the value (String) of the currentDate into the item in the array. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.