tags:

views:

32

answers:

2

Hi, 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.

+3  A: 

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.

Pointy
Fantastic, works a treat. Many thanks
bateman_ap
@Pointy: Will it work correctly if the day is the 31st of the month, since would be incrementing the month with `setMonth()`?
Daniel Vassallo
... Try using `new Date('2010-01-31')`... It will skip 'February'.
Daniel Vassallo
Oh hey good point!! I'll fix it
Pointy
+2  A: 

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;
})();
Daniel Vassallo
Yes this is a fine way to do it. Thanks! (I defer to the "Date" object to know when the end of a year is because I don't trust myself!)
Pointy
@Pointy: Lol! Not trusting ourselves is a very good practice :) ... Good idea to use `setDate(1)`. That's neater.
Daniel Vassallo