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

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


当前回答

怎么容易?

new Date().toLocaleString("en-US", { day: "2-digit" })

其他选项是可用的:

工作日 一年 月

更多信息请点击这里。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options

其他回答

("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}`
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD

我会这样做:

var date = new date (2000,0,9); var str = new Intl。DateTimeFormat(“en - us”{ 月:“便是”, 天:“便是”, 年:“数字” }) .format(日期); console.log (str);//打印“01/09/2000”

function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}