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

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


当前回答

如果你想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

其他回答

如果你想要一个像"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', ' ');
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD

date-fns。

import { lightFormat } from 'date-fns';
lightFormat(new Date(), '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;
}