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


当前回答

我经常使用的一段修改代码:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();

其他回答

我写了一个简单的函数,它可以将Date对象转换为具有日期号、月份号(带零填充)和年份号的可定制顺序的String。您可以将它与您喜欢的任何分隔符一起使用,或者将此参数保留为空以在输出中不显示分隔符。请看一看。

function dateToString(date, $1, $2, $3, separator='') { const dateObj = { date: String(date.getDate()).padStart(2, '0'), month: String(date.getMonth() + 1).padStart(2, '0'), year: date.getFullYear() }; return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3]; } const date = new Date(); const dateString1 = dateToString(date, 'year', 'month', 'date'); console.log(dateString1); // Manipulate arguments order to get output you want const dateString2 = dateToString(date, 'date', 'month', 'year', '-'); console.log(dateString2);

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

require (" datejs)

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

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

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"

有些日期=新日期(); =某物。 游戏机。log (dateFormated);

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'