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
Yes, get
String.js
by Rumata and then use:NB: don't forget the
+ 1
on the month field. TheDate
object's month field starts from zero, not one!If you don't want to use an extra library, a trivial inline function will do the job of adding the leading zeroes:
or even add it to the
Date
prototype:usage (see http://jsfiddle.net/alnitak/M5S5u/):
...and a sample: http://jsfiddle.net/gFkaP/
You will have to manually check if it needs a leading zero and add it if necessary...
The easiest way to do this is to prepend a
zero
and then use.slice(-2)
. With this function you always return the last 2 characters of astring
.var month = 8;
var monthWithLeadingZeros = ('0' + month).slice(-2);
Checkout this example: http://codepen.io/Shven/pen/vLgQMQ?editors=101
No, there is no nice way to do it. You have to resort to something like:
You can try like this
For day:
For month:
For year: