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

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


当前回答

const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD

其他回答

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

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

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;
}

如果你想要一个像"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', ' ');

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

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);
}
var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

为什么不用padStart ?

哪里有亭子

targetLength为2 padString为0

//来源:https://stackoverflow.com/a/50769505/2965993 var dt= new date(); year=dt.getfullyear(); month=(dt.getmonth()+1).tostring()。padStart(2,“0”); date().tostring()。padStart(2,“0”); log(year+'/'+ month+'/'+ day);

这将总是返回2位数字,即使月或日小于10。

注:

这将只适用于Internet Explorer,如果js代码是转译使用babel。 getFullYear()返回4位年份,不需要padStart。 getMonth()返回从0到11的月份。 在填充前将1添加到月份,以保持1到12。 getDate()返回从1到31的日期。 第7天将返回07,因此我们不需要在填充字符串之前添加1。