javascript - How to get Past 12months with year from current date - Stack Overflow

I want to show the past 12 months but year is not appending with the listvar theMonths = new Array(&quo

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 0
Add a ment  | 

2 Answers 2

Reset to default 7

If 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 :)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745379461a4625155.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信