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


当前回答

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

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"

其他回答

// utc / gmt 0 文档。write('UTC/GMT 0: ' + (new Date()). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812013509 //客户端本地时间 文档。write('<br/>本地时间:' + (new Date(Date.now()-(new Date()). gettimezoneoffset () * 60000)). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812113509

@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

似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

但我不确定是否值得只针对这个特定的任务。

很好,很简单:

    var date = new Date();
    var yyyy = date.getFullYear();
    var mm = date.getMonth() + 1; // getMonth() is zero-based
    if (mm < 10) mm='0'+mm;
    var dd = date.getDate();
    if (dd < 10) dd='0'+dd;
    /*date.yyyymmdd();*/

    console.log('test - '+yyyy+'-'+mm+'-'+dd);