I want to show the past 12 months but year is not appending with the list
var theMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var today = new Date();
var aMonth = today.getMonth();
var i;
for (i = 0; i < 12; i++) {
document.writeln(theMonths[aMonth] + '<br>'); //here you can do whatever you want...
aMonth++;
if (aMonth > 11) {
aMonth = 0;
}
}
I want to show the past 12 months but year is not appending with the list
var theMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var today = new Date();
var aMonth = today.getMonth();
var i;
for (i = 0; i < 12; i++) {
document.writeln(theMonths[aMonth] + '<br>'); //here you can do whatever you want...
aMonth++;
if (aMonth > 11) {
aMonth = 0;
}
}
How can I get the past 12 months with year from current month.
Share Improve this question edited Jan 17, 2018 at 10:52 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jan 17, 2018 at 10:42 Test1234Test1234 4071 gold badge7 silver badges20 bronze badges 02 Answers
Reset to default 7If you want to include the year with the output date then the simplest method is to add 1 month to the current date within your loop. You can then retrieve the month and year from that date within the loop, something like this:
var theMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var now = new Date();
for (var i = 0; i < 12; i++) {
var future = new Date(now.getFullYear(), now.getMonth() + i, 1);
var month = theMonths[future.getMonth()];
var year = future.getFullYear();
console.log(month, year);
}
Note that this loop, which is copied from your question, gets months in the future yet your description states you want to retrieve passed months. In that case you'd simply need to loop from 0
to > -12
instead, using i--
.
If I understand your question correctly, you want to track down the current month, then the month before it etc. judging from your sentence:
How can I get the past 12 months
Try replacing the code in your loop with this:
aMonth--;
if (aMonth < 0) {
aMonth = 11;
}
If that's not the case please elaborate your desired result in more details :)