简体   繁体   中英

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!

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());
}

Thank you all, I understood that everytime i change the curr value and that was the problem. All your solutions are working, but i'll prefer the simplest one, the one from @denisw, which I copy there for anybody else with the same problem :

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var firstday = (new Date(curr.setDate(first+1))).toString();
for(var i = 1; i < 7; i++) {
   var next = new Date(curr.getTime());
   next.setDate(first+i);
   alert(next.toString());                            
}

Once again, thank you all, for your quick answers and your help!

let curr = new Date;
let week = []

for (let i = 1; i <= 7; i++) {
  let first = curr.getDate() - curr.getDay() + i 
  let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
  week.push(day)
}
console.log('week:', week);

jsfidde: https://jsfiddle.net/sinh_nguyen/v9kszn2h/4/

You can add date and day . The former goes from 1 to 28..31 and the latter from 0 to 6. What should the Date type do if you set the date to -3?

The solution is to convert all values to milliseconds.

var ONE_DAY_IN_MILLIS = 1000*60*60*24;

var curr = new Date();

// Get offset to first day of week
// Note: Depending on your locale, 0 can be Sunday or Monday.
var offset = curr.getDay() * ONE_DAY_IN_MILLIS;

// Date at the start of week; note that hours, minutes and seconds are != 0
var start = new Date( curr.getTime() - offset );

for( var i=0; i<7; i++ ) {
    var nextDay = new Date( start.getTime() + ( i * ONE_DAY_IN_MILLIS ) );
    ...
}

The problem is that you are modifying your curr date and creating a new date at the same time. There are two ways to do this:

Either never modifiy your curr date object and create new Dates:

var msInDay = 1000 * 60 * 60 * 24;

function addDays(date, days) {
  return new Date(date.getTime() + days * msInDay);        
}

var curr = new Date();

var first = addDays(curr, -curr.getDay() + 1);

alert(first);

for(var i = 1; i<7; i++) {
    var next = addDays(first, i);
    alert(next);
}

Or modify your curr date object consistently:

var curr = new Date();

curr.setDate(curr.getDate() - curr.getDay() + 1);

alert(curr);

for(var i = 1; i<7; i++) {
    curr.setDate(curr.getDate() + 1);
    alert(curr);
}

​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM