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:35

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"
查看更多
【Aperson】
3楼-- · 2020-02-09 07:35

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.

查看更多
甜甜的少女心
4楼-- · 2020-02-09 07:36

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

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

查看更多
登录 后发表回答