jquery从给定日期开始查找前12个月的日期

时间:2016-06-17 16:27:20

标签: javascript jquery date

在这里,在jquery中,我试图找到自给定日期之前的12个月日期。但是,过去12个月的日期是错误的。

>     var now = new Date();
>     var months = new Array( "January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November",
> "December");
>     for(var i=0; i<=11;i++){
>     var past = now.setMonth(now.getMonth() -i);
>     console.log(months[now.getMonth()]+' '+now.getFullYear());
>     }

我的输出低于输出值。

June 2016
May 2016
March 2016
December 2015
August 2015
March 2015
September 2014
February 2014
June 2013
September 2012
November 2011
December 2010

2 个答案:

答案 0 :(得分:4)

你所要做的就是改变:

now.getMonth() - i

到此

now.getMonth() - 1

就是这样。因为您在循环的每次迭代中修改now,只需减去一个月而不是循环变量。

请参阅此处的工作示例:http://jsbin.com/nibizaqayu/edit?js,console

另请注意,此时past变量无效,因此您的循环可能如下所示:

for(var i=0; i<=11;i++){
   now.setMonth(now.getMonth() - 1);
   console.log(months[now.getMonth()]+' '+now.getFullYear());
}

另一种选择是创建一个新的Date实例,就像其他答案所示,并且它同样有效。但是我个人认为这更简单。

答案 1 :(得分:2)

当您在setMonth上致电now时,它会操纵该日期,因此下次进入循环时,它不再是now的原始值,而您是减去递增计数器。

可能的解决方案是在循环中存储基于now的新日期对象,然后操纵它,只留下now ...

var now = new Date();
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for (var i = 0; i <= 11; i++) {
    var past = new Date(now); // @talemyn ;)
    past.setMonth(now.getMonth() - i);
    console.log(months[past.getMonth()] + ' ' + past.getFullYear());
}

...或者您可以now的增量设置1的值,而不是i ......

var now = new Date();
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for (var i = 0; i <= 11; i++) {
    console.log(months[now.getMonth()] + ' ' + now.getFullYear());
    var past = now.setMonth(now.getMonth() - 1);
}