Javascript date - Leading 0 for days and months wh

2020-02-09 06:35发布

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条回答
我只想做你的唯一
2楼-- · 2020-02-09 07:16

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();
查看更多
▲ chillily
3楼-- · 2020-02-09 07:20
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/

查看更多
我命由我不由天
4楼-- · 2020-02-09 07:21

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;
查看更多
不美不萌又怎样
5楼-- · 2020-02-09 07:25

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

查看更多
叛逆
6楼-- · 2020-02-09 07:32

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;
查看更多
beautiful°
7楼-- · 2020-02-09 07:32

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();
查看更多
登录 后发表回答