我试图使用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 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"
我经常使用的一段修改代码:
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();
我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。
函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));
小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/
似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
但我不确定是否值得只针对这个特定的任务。
Dateformat是一个非常常用的包。
使用方法:
从NPM下载并安装dateformat。在你的模块中需要它:
以格式
然后格式化你的东西:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');