原生 Date 缺乏靈活的格式化輸出,擴展 Date.prototype.format 可支援 YYYY-MM-DD hh:mm:ss 等任意模板,極大提升開發效率。
Date.prototype.format = function(fmt) {
const o = {
'M+': this.getMonth() + 1, // 月
'd+': this.getDate(), // 日
'h+': this.getHours(), // 時
'm+': this.getMinutes(), // 分
's+': this.getSeconds(), // 秒
'q+': Math.floor((this.getMonth() + 3) / 3), // 季
'S': this.getMilliseconds() // 毫秒
};
// 年份特殊處理:YYYY / YY
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
// 其他字段:自動補零
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
}
}
return fmt;
};
// 使用示例
console.log(new Date().format('YYYY-MM-dd hh:mm:ss.S')); // 2024-05-18 14:30:05.123
console.log(new Date().format('YYYY年M月d日')); // 2024年5月18日
RegExp.$1 捕獲模板中的佔位符長度,決定是否補零。o 對象添加鍵值即可支援新格式(如週 W)。修改內建原型在大型團隊項目中可能引發命名衝突,建議封裝為獨立工具函數 formatDate(date, fmt) 或使用 ES Module 導出,避免污染全局 Date。