date – Determine month -3 and +3 in JavaScript – Education Career Blog

Hey,
Easy question, my brain is empty today..
I have a array with month(1-12) and a given month.

var cMonate = new Array("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli",
                            "August", "September", "Oktober", "November", "Dezember");

My given month:

var Month = currentMonth.getMonth(); 

Month is 8. Now I will read the last 3 month and the coming month.

Easy sample:
may
june
july
august
september
october
november

How can I find out ?

,

for(var m = Month - 3; m <= Month + 3) {
  var usedMonth = (m < 1 ? m + 12 : (m > 12 ? m - 12 : m));
  // use 'usedMonth' here for whatever...e.g.:
  console.log(cMonateusedMonth-1);
}

,

Are you aware of datejs?

,

Regard your months as an infinite series, starting from -infinity, going to -3, -2, -1, 0, 1, 2, …, 12, 13, 14, …

Then it’s easy:

for( var infindex = monthindex-3; infindex < month+4; ++infindex ) {
   return month( infindex );
}

Then you can create a mapping from the infinite index to the ever-recurring sequence:

function month( infiniteindex ) {
  var index = infinteindex % 12; // since every 12 months, the same month occurs.
  // EDIT --- javascript allows negative result for modulo
  if( index < 0 ) index = index+12;
  return cMonateindex;
}

Leave a Comment