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

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


当前回答

更现代的方法可能是使用"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}`

其他回答

我想做这样的事情,这就是我所做的

附注:我知道上面有正确答案,但我只是想在这里补充一些我自己的东西

const todayIs = async () =>{
    const now = new Date();
    var today = now.getFullYear()+'-';
    if(now.getMonth() < 10)
        today += '0'+now.getMonth()+'-';
    else
        today += now.getMonth()+'-';
    if(now.getDay() < 10)
        today += '0'+now.getDay();
    else
        today += now.getDay();
    return today;
}

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

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

为例:

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

另外一个版本在这里https://jsfiddle.net/ivos/zcLxo8oy/1/,希望对大家有用。

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")

如果你想要一个像"YYYY-MM-DDTHH:mm:ss"这样的格式,那么这可能会更快:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ

或者常用的MySQL日期时间格式“YYYY-MM-DD HH:mm:ss”:

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');

不是一个答案,但这里是我如何得到我在一个变量中需要的日期格式

function setDateZero(date){
  return date < 10 ? '0' + date : date;
}

var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);

希望这能有所帮助!