user1397157
user1397157

Reputation: 25

jquery find previous 12 months date from given date

Here , In jquery I am trying to find previous 12 month date from given date. but, the previous 12 months dates are wrong.

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

I am getting below output.

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

Upvotes: 2

Views: 2014

Answers (2)

jszobody
jszobody

Reputation: 28911

All you have to do is change:

now.getMonth() - i

To this

now.getMonth() - 1

That's it. Because you're modifying now in each iteration of your loop, just subtract one month instead of the loop variable.

See working example here: http://jsbin.com/nibizaqayu/edit?js,console


Also note that your past variable is doing nothing at this point, so your loop can look like this:

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

Another option would be to create a new Date instance as the other answers have shown, and it works equally well. However I personally find this to be simpler.

Upvotes: 4

Billy Moon
Billy Moon

Reputation: 58531

When you call setMonth on now it manipulates that date, so next time you enter the loop, it's no longer the original value of now, and you are subtracting an incrementing counter.

Potential solution is to store new date object based off now in loop, then manipulate that, leaving now alone...

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

... or you could set the value of now in increments of 1 instead of 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);
}

Upvotes: 2

Related Questions