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


当前回答

如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:

$.datepicker.formatDate('yymmdd', new Date());

我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。

更多示例请访问http://api.jqueryui.com/datepicker/

其他回答

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

我试图写一个简单的库操作JavaScript日期对象。你可以试试这个。

var dateString = timeSolver.getString(date, "YYYYMMDD")

Libarary: https://github.com/sean1093/timeSolver

js有很多有用的日期解析方法。

require (" datejs)

(新的日期()).toString(“名称”)

const date = new Date()

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

日期短代码拯救!

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'