我试图使用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

其他回答

对公认答案的一点变化:

函数getDate_yyyymmdd() { const date = new date (); const yyyy = date.getFullYear(); const mm = String(date.getMonth() + 1).padStart(2,'0'); const dd = String(date.getDate()).padStart(2,'0'); 返回“$ {yyyy} $ {mm} $ {dd} ' } console.log (getDate_yyyymmdd ())

除了o-o的答案之外,我还建议将逻辑操作与返回值分离,并将它们作为三元放入变量中。

另外,使用concat()来确保变量的安全连接

Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); return "".concat(yyyy).concat(mm).concat(dd); }; Date.prototype.yyyymmddhhmm = function() { var yyyymmdd = this.yyyymmdd(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); return "".concat(yyyymmdd).concat(hh).concat(min); }; Date.prototype.yyyymmddhhmmss = function() { var yyyymmddhhmm = this.yyyymmddhhmm(); var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds(); return "".concat(yyyymmddhhmm).concat(ss); }; var d = new Date(); document.getElementById("a").innerHTML = d.yyyymmdd(); document.getElementById("b").innerHTML = d.yyyymmddhhmm(); document.getElementById("c").innerHTML = d.yyyymmddhhmmss(); <div> yyyymmdd: <span id="a"></span> </div> <div> yyyymmddhhmm: <span id="b"></span> </div> <div> yyyymmddhhmmss: <span id="c"></span> </div>

var dateDisplay = new Date( 2016-11-09 05:27:00 UTC );
dateDisplay = dateDisplay.toString()
var arr = (dateDisplay.split(' '))
var date_String =  arr[0]+','+arr[1]+' '+arr[2]+' '+arr[3]+','+arr[4]

这将显示像Wed,Nov 09 2016,10:57:00这样的字符串

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

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

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

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

require (" datejs)

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