当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:

对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?


当前回答

最好的方法是创建自己的简单格式化器(如下所示):

getDate()返回每月的日期(从1-31) getMonth()返回月份(从0到11)<从零开始,0=一月,11=十二月 getFullYear()返回年份(4位数字)<不要使用getYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}

其他回答

我的解决方案:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

用法:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/

这里的答案很有帮助,但我需要的不仅仅是一个默认名称:月、日、月、小时和秒。

有趣的是,虽然以上都需要“0”的前缀,但只有month需要“+ 1”,其他都不需要。

为例:

("0" + (d.getMonth() + 1)).slice(-2)     // Note: +1 is needed
("0" + (d.getHours())).slice(-2)         // Note: +1 is not needed

如果你想getDate()函数返回日期为01而不是1,这里是它的代码.... 让我们假设今天的日期是2018年01月11日

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01
("0" + this.getDate()).slice(-2)

对于日期,类似的:

("0" + (this.getMonth() + 1)).slice(-2)

这个月。

更现代的方法可能是使用"padStart"

const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();

然后,如果你愿意,你可以构建一个模板字符串:

`${day}/${month}/${year}`