28

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
Harry
  • 13,091
  • 29
  • 107
  • 167

9 Answers9

29

The format you seem to want looks like ISO. So take advantage of toISOString():

var d = new Date();
var date = d.toISOString().slice(0,10); // "2014-05-12"
mivk
  • 13,452
  • 5
  • 76
  • 69
23

No, there is no nice way to do it. You have to resort to something like:

var myDate = new Date();

var year = myDate.getFullYear();

var month = myDate.getMonth() + 1;
if(month <= 9)
    month = '0'+month;

var day= myDate.getDate();
if(day <= 9)
    day = '0'+day;

var prettyDate = year +'-'+ month +'-'+ day;
Paul
  • 139,544
  • 27
  • 275
  • 264
  • 2
    Months are zero-indexed in `Date`, so this would shift any month down by one notch (as well as create invalid dates in the case of january). – sandstrom Feb 12 '13 at 10:44
8
var myDate = new Date();
var m = myDate.getMonth() + 1;
var d = myDate.getDate();
m = m > 9 ? m : "0"+m;
d = d > 9 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;

...and a sample: http://jsfiddle.net/gFkaP/

Makram Saleh
  • 8,613
  • 4
  • 27
  • 44
6

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();
Bablu Ahmed
  • 4,412
  • 5
  • 49
  • 64
3

You will have to manually check if it needs a leading zero and add it if necessary...

var m = myDate.getMonth();
var d =  myDate.getDate();

if (m < 10) {
    m = '0' + m
}

if (d < 10) {
    d = '0' + d
}

var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
Eric
  • 95,302
  • 53
  • 242
  • 374
Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
2

Yes, get String.js by Rumata and then use:

'%04d-%02d-%02d'.sprintf(myDate.getFullYear(),
                         myDate.getMonth() + 1,
                         myDate.getDate());

NB: don't forget the + 1 on the month field. The Date 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:

function date2str(d) {
    function fix2(n) {
        return (n < 10) ? '0' + n : n;
    }
    return d.getFullYear() + '-' +
           fix2(d.getMonth() + 1) + '-' +
           fix2(d.getDate());
 }

or even add it to the Date prototype:

Date.prototype.ISO8601date = function() {
    function fix2(n) {
        return (n < 10) ? '0' + n : n;
    }
    return this.getFullYear() + '-' +
           fix2(this.getMonth() + 1) + '-' +
           fix2(this.getDate());
 }

usage (see http://jsfiddle.net/alnitak/M5S5u/):

 var d = new Date();
 var s = d.ISO8601date();
Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

For Month, var month = ("0" + (myDate.getMonth() + 1)).slice(-2);

For Day, var day = ("0" + (myDate.getDate() + 1)).slice(-2);

Arsalan
  • 461
  • 3
  • 12
0

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 a string.

var month = 8;

var monthWithLeadingZeros = ('0' + month).slice(-2);

Checkout this example: http://codepen.io/Shven/pen/vLgQMQ?editors=101

Shven
  • 11
  • 3
0

Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.

var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
        if (String(dateNumber).length === 1) {
            return '0' + String(dateNumber);
        }

        return String(dateNumber);
    },
    myDate = new Date(),
    prettyDate;

prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());

EDIT

As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.

fredrik
  • 17,537
  • 9
  • 51
  • 71
  • your code won't work - numbers don't have a `.length` property. – Alnitak Aug 08 '11 at 09:13
  • I get an incorrect month, and twice as much source code as necessary. Compare with `date2str` in my answer. – Alnitak Aug 08 '11 at 09:29
  • It depends of what month you pass to the method, this method is for adding a leading 0 where needed, not handle the month. Single responsibility. But I'll add it for clarification. But the twice amount of code is for readability, not optimization. – fredrik Aug 08 '11 at 09:39
  • JS months start at zero, not one. Your code (like many of the answers here, as well as the OP's code) will show the wrong number. – Alnitak Aug 08 '11 at 09:41