0

Using moment.js, i need to build an array of the coming 12 months.- starting from the current month. e.g (assuming current month = December):

var monthsArray = [
  "December",
  "January",
  "February",
  "March",
  [...]
  "November"
  ]

My current solution only displays all 12 months of a year, without considering a "starting" month

  var count = 0;
  var months = [];
  while (count < 12) months.push(moment().month(count++).format("MMMM"));

I guess the user month with

_private.userMonth = moment().format('MMMM');

How can i apply this to build my array of months?

Rene Füchtenkordt
  • 137
  • 1
  • 3
  • 14

2 Answers2

2

How about this, among all kinds of other ways to do it.

var months = moment.months();
var coming12Months = months.concat(months.slice(0, moment().month())).slice(-12);

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

This is not a particularly elegant solution, but it's effective. A thread on how to properly rotate an array in JS over here.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
0

You can just use moment's add function:

var offset = 0;
var months = [];
while (offset < 12) {
  months.push(moment().add(offset++, 'month').format('MMMM'));
}
adrice727
  • 1,482
  • 12
  • 17