如何通过javascript中的currentDate在一周内获得7天? [英] How to get the 7 days in a week with a currentDate in javascript?

查看:354
本文介绍了如何通过javascript中的currentDate在一周内获得7天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(首先,对于我不好的英语,我是初学者)

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

我有按日期排列的百分比图表。我想在x轴上显示本周的每一天。

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 ..."

所以,你可以看到,它切换星期五和...奇怪的是它切换到好的日期... 4周后...

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.

谢谢!

推荐答案

恐怕你已经陷入了许多陷阱的对象突变之一。 :)

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

问题是,在var nextday = ...行中,您正在每次迭代中更改保存在curr中的日期,方法是调用 setDate()。只要下一个在当月的范围内,这是没有问题的; curr.setDate(next)相当于在这种情况下前进。

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.

问题开始于下一个到达30.没有2月30日,所以setDate()包裹到下个月,产生3月1日 - 到目前为止这么好。不幸的是,下一次迭代调用 curr.setDate(31),而 curr 是3月1日(请记住, curr 在每次迭代中改变),我们得到... 3月31日!其他奇怪的值可以解释相同的方式。

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.

解决这个问题的一种方法是在每次迭代中复制 curr ,然后 调用setDate(),如下所示:

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

这篇关于如何通过javascript中的currentDate在一周内获得7天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆