Javascript date - Leading 0 for days and months where applicable

Viewed 38206

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:

var myDate = new Date();
var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate();

This would output as:

2011-8-8

I would like it to be:

2011-08-08
9 Answers

You can try like this

For day:

("0" + new Date().getDate()).slice(-2)

For month:

("0" + (new Date().getMonth() + 1)).slice(-2)

For year:

new Date().getFullYear();
Related