我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:
new Date().format("{yyyy}{MM}{dd}")
其他回答
// 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
下面是一种更通用的方法,它允许日期和时间组件,并且可以作为数字或字符串进行相同的排序。
根据“Date ISO format”中的数字顺序,转换为本地时区,去掉非数字。例如:
// monkey patch version
Date.prototype.IsoNum = function (n) {
var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}
使用
var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8)); // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum()); // "20150728150253272"
对公认答案的一点变化:
函数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的答案,这将根据格式字符串返回日期的字符串。如果你需要的话,你可以很容易地为年份和毫秒添加一个2位数的年份正则表达式。
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
然而,我不知道这有多高效,特别是在性能方面,因为它使用了大量的正则表达式。它可能会使用一些我不掌握纯js的工作。
注意:我保留了预定义的类定义,但你可能想把它放在一个函数或自定义类根据最佳实践。
如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:
$.datepicker.formatDate('yymmdd', new Date());
我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。
更多示例请访问http://api.jqueryui.com/datepicker/