How to add the string "0" in the month / day of the date?

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

I am trying to figure out how to add “0” before months that are less than 10. Also, how can I add “0” in front on days that are less than ten,

Currently, when it returns an object (2012-6-9). It returns 6 and 9 without a “0” in front of it, can someone show me how to do this?

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('-'); }; 
+4
source share
3 answers

You can also avoid testing if n <10 using:

 ("0" + (yourDate.getMonth() + 1)).slice(-2) 
+13
source

you can write a small function as follows:

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

and pass him the month and day

 return [date.getFullYear(),pad(date.getMonth() + 1), pad(date.getDate())].join('-'); 
+2
source

Try doing "0":

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

All Articles