4

so i wrote up a method that takes a number and subtracts the amount of months from the current date.

I am trying to figure out how can i add a '0' in front of the months that are less that 10. Also, how can I add a '0' in front on the days that are less than ten as well.

Currently, when it returns the object (2012-6-9). It returns 6 and 9 with no '0' in front of it, can someone show me how to do it?

Here is my code

lastNmonths = function(n) {
    var date = new Date();

    if (n <= 0)
        return [date.getFullYear(), date.getMonth() + 1 , date.getDate()].join('-');
    var years = Math.floor(n/12); 


   var months = n % 12;


    if (years > 0)
        date.setFullYear(date.getFullYear() - years);

    if (months > 0) {
        if (months >= date.getMonth()) {
            date.setFullYear(date.getFullYear()-1 );
            months = 12 - months; 
            date.setMonth(date.getMonth() + months );
        } else {
            date.setMonth(date.getMonth() - months);
        }
    }

}

    return [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-');
};
user2079233
  • 41
  • 1
  • 1
  • 2
  • See http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript for some suggestions about how to convert a date to a string – Grim Feb 16 '13 at 22:20
  • [Javascript add leading zeroes to date](http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date) – the system Feb 16 '13 at 22:24

3 Answers3

14

You can also avoid testing if n < 10 by using :

("0" + (yourDate.getMonth() + 1)).slice(-2)
Arnaud Christ
  • 3,440
  • 3
  • 24
  • 33
2

you can write a little function like this :

function pad(n) {return (n<10 ? '0'+n : n);}

and pass month and day to it

return [date.getFullYear(),pad(date.getMonth() + 1), pad(date.getDate())].join('-');
srosh
  • 124
  • 1
  • 3
0

Try concat the "0":

   month = date.getMonth() + 1 < 10 ? '0' + date.getMonth() + 1 : date.getMonth() + 1
   return [date.getFullYear(), month, date.getDate()].join('-');
imalvinz
  • 89
  • 4