Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the 7 days in a week with a currentDate in javascript?

(first, sorry for my bad english, i'm a beginner)

I have a chart of percent by date. I would like to display every day of the current week in the x-axis.

So, i tried to find how to get the seven days of the week. that's what i have :

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();//to set first day on monday, not on sunday, first+1 :

var firstday = (new Date(curr.setDate(first+1))).toString();

for(var i = 1;i<7;i++){
var next = first + i;
var nextday = (new Date(curr.setDate(next))).toString();
alert(nextday);
}

the alert begins well...until the end of the month. That's what i got :

1 : "Mon 27 Feb 2012 ..."
2 : "Tue 28 Feb 2012 ..."
3 : "Wed 29 Feb 2012 ..."
4 : "Thu 01 Mar 2012 ..."
5 : "Sat 31 Mar 2012 ..."
6 : "Sun 01 Apr 2012 ..."

So, as you can see, it switches the friday and... strangely it switch to the good date...4 weeks later...

So, do you have a better solution for me, or maybe you could just help me and say what is the problem.

Thank you!

like image 326
Gaelle Avatar asked Oct 09 '22 13:10

Gaelle


1 Answers

I'm afraid you have fallen into one of the numerous traps of object mutation. :)

The problem is that, in the line "var nextday = ...", you are changing the date saved in "curr" on every iteration by calling setDate(). That is no problem as long as next is within the range of the current month; curr.setDate(next) is equivalent to going forward one in this case.

The problems begin when next reaches 30. There is no February 30, so setDate() wraps around to the next month, yielding the 1st of March - so far so good. Unfortunately, the next iteration calls curr.setDate(31), and as curr is the 1st of March (remember that the object referenced by curr is changed in each iteration), we get... March 31! The other strange values can be explained the same way.

A way to fix this is to copy curr on each iteration and then call setDate(), like so:

for (var i = 1; i < 7; i++) {
    var next = new Date(curr.getTime());
    next.setDate(first + i);
    alert(next.toString());
}
like image 126
Denis Washington Avatar answered Oct 12 '22 09:10

Denis Washington