Date 物件可擴充 format 方法,讓日期輸出成指定格式。常見格式包括年、月、日、時、分、秒與毫秒。
以下範例透過正則表達式替換格式字串,將 Date 物件轉為 yyyy-MM-dd 等可讀格式。
Date.prototype.format = function (format) {
var o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds()
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
}
}
return format;
};
console.log(new Date().format('yyyy-MM-dd'));