把 Date 物件格式化成 2026-08-26 20:14:00 這類字串,是每個專案都會遇到的需求。本文的實作用「模式字元比對 + 逐項替換」的通用思路,一支函式就能應付各種格式。
function dateFormat(date, format) {
var o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"h+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
};
//把 yyyy 替換成具體的年份
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.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 ? (("000" + o[k]).substr(("" + o[k]).length)) : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
年份單獨處理。因為 y 的長度決定要取幾位數,邏輯與其他欄位不同,所以另外判斷。用 substr(4 - 模式長度) 從年份字串右側取:yyyy 取 4 位、yy 取後 2 位。
其餘欄位靠補零對齊。關鍵是那段「"000" + 值 再 substr」的技巧。以月份 8、模式 MM 為例:"00" + "8" 得到 "008",再從索引 1 開始取(值的長度 1),得到 "08"。若模式是單一的 M,則從索引 1 取「000」+「8」=「0008」的後面部分,剛好得到 "8"。兩種情況共用同一段表達式,是這個寫法最巧妙之處。
q(季度)用 (month + 3) / 3 後取整數:1~3 月得 1、4~6 月得 2,依此類推。
dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"); // 2026-08-26 20:14:00
dateFormat(new Date(), "yy年M月d日"); // 26年8月26日
dateFormat(new Date(), "yyyy年第q季度"); // 2026年第3季度
一、getMonth() 從 0 起算。所以必須 +1,這是最常見的月份差一個月的 bug 來源。
二、12 小時制沒有 AM/PM。這個版本只有 h(24 小時制),若需要 12 小時制要自己做 date.getHours() % 12 || 12 的轉換並補上 AM/PM。
三、RegExp.$1 已不建議使用。這些靜態屬性狀態不明且效能不佳,改用函式形式的 replace 更清楚:
format = format.replace(/(y+)/, (_, p) => (date.getFullYear() + '').slice(-p.length));
Intl.DateTimeFormat 是瀏覽器內建、支援多語言與各地曆法的標準方案:
new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
}).format(new Date());
要自訂任意模式字串,toLocaleString 搭配 locales 參數,或直接取 date.toISOString() 後切片(注意那是 UTC)。這個自製函式的價值在於「不依賴任何外部資源、邏輯透明」,在受限環境中仍很好用;但正式專案若涉及多時區、多語言或閏秒等邊界,交給 Intl 或 Day.js、date-fns 會更穩妥。