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


当前回答

这篇文章帮助我写了这个助手,所以我分享它以防有人 正在寻找这个解决方案,它支持yyyy, mm, dd的所有变化

Date.prototype.formattedDate = function (pattern) {
    formattedDate = pattern.replace('yyyy', this.getFullYear().toString());
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
    mm = mm.length > 1 ? mm : '0' + mm;
    formattedDate = formattedDate.replace('mm', mm);
    var dd = this.getDate().toString();
    dd = dd.length > 1 ? dd : '0' + dd;
    formattedDate = formattedDate.replace('dd', dd);
    return formattedDate;
};

d = new Date();
pattern = 'yyyymmdd';  // 20150813
d.formattedDate(pattern);

pattern = 'yyyy-mm-dd';
d.formattedDate(pattern); // 2015-08-13

其他回答

当地时间:

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 ' '中,你可以添加空格、点或任何你喜欢的东西。

如果使用AngularJs(最多1.5),你可以使用日期过滤器:

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')

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

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

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

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

当然,您可以为日期字符串表示形式的每种变化构建特定的函数。如果您考虑国际日期格式,那么您会得到几十个名称荒谬且难以区分的特定函数。

没有匹配所有格式的合理函数,但有一个合理的函数组合:

const pipe2 = f => g => x => g(f(x)); const pipe3 = f => g => h => x => h(g(f(x))); const invoke = (method, ...args) => o => o[method] (...args); const padl = (c, n) => s => c.repeat(n) .concat(s) .slice(-n); const inc = n => n + 1; // generic format date function const formatDate = stor => (...args) => date => args.map(f => f(date)) .join(stor); // MAIN const toYYYYMMDD = formatDate("") ( invoke("getFullYear"), pipe3(invoke("getMonth")) (inc) (padl("0", 2)), pipe2(invoke("getDate")) (padl("0", 2))); console.log(toYYYYMMDD(new Date()));

是的,这是一大堆代码。但是,您可以通过简单地更改传递给高阶函数formatDate的函数参数来逐字地表示每个字符串日期表示。一切都是显式的和声明性的,也就是说,你几乎可以读到发生了什么。