我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
有些日期=新日期(); =某物。 游戏机。log (dateFormated);
其他回答
当地时间:
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 ' '中,你可以添加空格、点或任何你喜欢的东西。
这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。
如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。
如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:
$.datepicker.formatDate('yymmdd', new Date());
我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。
更多示例请访问http://api.jqueryui.com/datepicker/
这篇文章帮助我写了这个助手,所以我分享它以防有人 正在寻找这个解决方案,它支持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 ())