Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Print previous 12 months -- "March" prints twice?

Tags:

javascript

I'm trying to write a script that prints the names of the previous 12 months. Since this month is January, it should print: December November October September August July June May April March February January

Instead, it prints March twice. http://jsfiddle.net/h69gm04g/2/

November October September August July June May April March March February

HTML

    <div id="test"></div>

Javascript

    monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
    d = new Date();

    for (i = 0; i < 12; i++) {  
        d.setMonth(d.getMonth() - 1);      
        monthName = monthNames[d.getMonth()];       
        $('#test').append(monthNames[d.getMonth()] + "<br>");       
    }

What am I doing wrong?

like image 841
Tyler Burleigh Avatar asked Jan 29 '15 19:01

Tyler Burleigh


4 Answers

Nice one! Took me a while.

The reason for this is that today is the 29th. Since your date object is set to the current day implicitly and February only had 28 days in 2013, you see March printed twice. Fix this by setting the optional day parameter:

d.setMonth(d.getMonth() - 1, 1);
like image 100
aaronk6 Avatar answered Oct 20 '22 00:10

aaronk6


That's because today happens to be the 29th, and when you get to february the 29th it will wrap over into march.

Set the date to the 1st (or any other date that is less than 29), then it works for all months:

d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);

Demo: http://jsfiddle.net/h69gm04g/3/

like image 22
Guffa Avatar answered Oct 19 '22 22:10

Guffa


I don't think there's any reason for answers that manipulate a Date object on each iteration. Once we know the current month, all we need to do is iterate the list backwards, wrapping around at the end. That's a job for %. Unfortunately, % does not do a true mathematical mod operation, and can return a negative value, so the easiest implementation is to ensure that the value is positive by adding an additional 12 to it:

var month = new Date().getMonth();

for (i = 1; i <= 12; i++) {
    $('#test').append(monthNames[(12 + month - i) % 12] + "<br>");            
}

(JSFiddle)

like image 3
Scott Sauyet Avatar answered Oct 19 '22 22:10

Scott Sauyet


Try this http://jsfiddle.net/oLp9hegk/:

monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

m = (new Date()).getMonth();
for (var i = 0; i < 12; i++) {
    $('#test').append(monthNames[(m-i+11)%12] + "<br>");       
}
like image 1
hattman Avatar answered Oct 20 '22 00:10

hattman