我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

原生Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');

其他回答

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'

当地时间:

var date = new Date();
date = date.toJSON().slice(0, 10);

UTC时间:

var date = new Date().toISOString();
date = date.substring(0, 10);

在我写这篇文章的时候,日期将在今天2020-06-15打印出来。

toISOString()方法返回ISO标准的日期,YYYY-MM-DDTHH:mm:ss.sssZ

代码采用YYYY-MM-DD格式所需的前10个字符。

如果你想要没有'-'的格式,请使用:

var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;

在.join ' '中,你可以添加空格、点或任何你喜欢的东西。

const date = new Date()

console.log(date.toISOString().split('T')[0]) // 2022-12-27

@o-o解对我没用。 我的解决方案如下:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();
  var ret = [this.getFullYear(), (mm<10)?'0':'', mm, (dd<10)?'0':'', dd].join('');

  return ret; // padding
};

Day.js怎么样?

它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。

https://github.com/iamkun/dayjs