bateman_ap
bateman_ap

Reputation: 1921

Setting month and year values for the next 6 months in Javascript

I am using a rather nice iPhone date control for a iPhone only website I am developing: 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. To hard code this I used:

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 one '05-2010': 'Jun 2010'

05 is the month value 2010 is the year and Jun is the month name

But obviously this is no use as it isn't going to work next month! But I'm stumped how to get this to work dynamically. Any help appreciated.

Upvotes: 3

Views: 353

Answers (2)

Daniel Vassallo
Daniel Vassallo

Reputation: 344431

The following should avoid problems when adding a month to the last day of a month ending on a 31st:

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;
})();

Upvotes: 2

Pointy
Pointy

Reputation: 413826

The Javascript Date object has all the APIs you need.

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;
})();

This will definitely work properly over the year boundary, by the way.

Upvotes: 3

Related Questions