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


当前回答

这里有一个简洁的小函数,易于阅读,并避免了局部变量,这在JavaScript中可能是时间消耗。我不使用原型来修改标准模块,因为它会污染名称空间,并可能导致代码不能执行您认为应该执行的操作。

main函数有一个愚蠢的名字,但它传达了思想。

function dateToYYYYMMDDhhmmss(date) {
    function pad(num) {
        num = num + '';
        return num.length < 2 ? '0' + num : num;
    }
    return date.getFullYear() + '/' +
        pad(date.getMonth() + 1) + '/' +
        pad(date.getDate()) + ' ' +
        pad(date.getHours()) + ':' +
        pad(date.getMinutes()) + ':' +
        pad(date.getSeconds());
}

其他回答

如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:

new Date().format("{yyyy}{MM}{dd}")

我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。

函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));

小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/

从ES6开始,你可以使用模板字符串使它更短:

var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;

这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。

当我需要这样做时,我通常使用下面的代码。

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

为了解释,.slice(-2)给出了字符串的最后两个字符。

所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。

所以如果MyDate.getMonth()返回9,它将是:

("0" + "9") // Giving us "09"

加上。slice(-2)就得到了最后两个字符:

("0" + "9").slice(-2)

"09"

但是如果date.getMonth()返回10,它将是:

("0" + "10") // Giving us "010"

所以加上.slice(-2)会得到最后两个字符,或者:

("0" + "10").slice(-2)

"10"

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