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?
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);
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/
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)
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>");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With