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

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


当前回答

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

其他回答

来自MDN的建议:

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/

("0" + this.getDate()).slice(-2)

对于日期,类似的:

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

这个月。

如果你检查的是小于10的,你不需要为它创建一个新函数。只需将变量赋值到括号中,并返回一个三元操作符。

(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`

只是另一个例子,几乎是一行。

var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+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', ' ');