Setting month and year over the next 6 months in Javascript

I use pretty nice date controls on iPhone for iPhone, which I just create: http://cubiq.org/spinning-wheel-on-webkit-for-iphone-ipod-touch

One of the wheels I want to create is basically the next 6 months with the month and year displayed. For hard code, I used this:

var monthsYears = { 
    '05-2010': 'Jun 2010', 
    '06-2010': 'Jul 2010', 
    '07-2010': 'Aug 2010', 
    '08-2010': 'Sep 2010', 
    '09-2010': 'Oct 2010', 
    '10-2010': 'Nov 2010' 
};

If i take the first '05-2010': 'Jun 2010'

05- this is the value of the month 2010- the year, and Jun- the name of the month

But obviously this is useless, as it will not work next month! But I do not understand how to make this work dynamically. Any help was appreciated.

+3
source share
2 answers

, 31-:

var monthsYears = (function () {
   var result = {};
   var d = new Date();
   var monthsStr = [
      'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
   ];
   var month = d.getMonth();
   var year = d.getFullYear();
   var padding = '';

   for (i = 0; i <= 5; i++) {
      padding = month < 9 ? '0' : '';
      result[padding + (month + 1) + '-' + year] = monthsStr[month] + ' ' + year;

      if (++month > 11) {
         month = 0;
         year++;
      }
   }

   return result;
})();
+2

Javascript Date API.

var monthsYears = (function() {
  var d = new Date(), rv = {},
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  d.setDate(1); // handle February!!
  for (var n = 1; n <= 6; ++n) {
    var mn = d.getMonth() + 1;
    mn = (mn < 10 ? '0' : '') + mn;
    rv[ '' + mn + '-' + d.getFullYear()] =
      months[d.getMonth()] + ' ' + d.getFullYear();
    d.setMonth(d.getMonth() + 1);
  }
  return rv;
})();

, , .

+3

Source: https://habr.com/ru/post/1748526/


All Articles