JS 原生 Date 格式化功能極弱,常需自寫格式化函數。本文提供一個健壯、支援任意格式字串(如 yyyy-MM-dd HH:mm:ss.S)的 dateFormat 函數,並說明原理與現代替代方案。
/**
* 日期格式化
* @param {Date|number|string} date 日期物件/時間戳/可解析字串
* @param {string} format 格式字串,支援:y/M/d/h/m/s/q/S
* @returns {string} 格式化後字串
*/
function dateFormat(date, format = 'yyyy-MM-dd HH:mm:ss') {
if (!(date instanceof Date)) date = new Date(date);
if (isNaN(date)) return 'Invalid Date';
const o = {
'M+': date.getMonth() + 1, // 月份 1-12
'd+': date.getDate(), // 日期 1-31
'h+': date.getHours(), // 小時 0-23
'm+': date.getMinutes(), // 分鐘 0-59
's+': date.getSeconds(), // 秒 0-59
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 1-4
'S' : date.getMilliseconds() // 毫秒 0-999
};
// 年份處理:yyyy / yy
if (/(y+)/.test(format)) {
const yearStr = date.getFullYear().toString();
format = format.replace(RegExp.$1, yearStr.slice(4 - RegExp.$1.length));
}
// 其他欄位:支援單字元 (M) 或雙字元 (MM) 自動補零
for (const k in o) {
if (new RegExp(`(${k})`).test(format)) {
const val = o[k].toString();
const len = RegExp.$1.length;
const replacement = len === 1 ? val : val.padStart(len, '0');
format = format.replace(RegExp.$1, replacement);
}
}
return format;
}
const now = new Date();
console.log(dateFormat(now)); // 2024-12-19 14:30:05
console.log(dateFormat(now, 'yyyy/MM/dd')); // 2024/12/19
console.log(dateFormat(now, 'yy-M-d h:m:s')); // 24-12-19 14:30:5
console.log(dateFormat(now, 'yyyy年MM月dd日')); // 2024年12月19日
console.log(dateFormat(now, 'HH:mm:ss.SSS')); // 14:30:05.123
console.log(dateFormat('2023-01-01', 'q')); // 1 (第一季)
| 字元 | 含義 | 範例 |
|---|---|---|
| y / yy / yyyy | 年份 (兩位/四位) | 24 / 2024 |
| M / MM | 月份 (不補零/補零) | 1 / 01 |
| d / dd | 日期 | 5 / 05 |
| h / hh | 小時 (24制) | 9 / 09 |
| H / HH | 小時 (12制,需自行擴充) | -- |
| m / mm | 分鐘 | 3 / 03 |
| s / ss | 秒 | 7 / 07 |
| q | 季度 | 1-4 |
| S / SS / SSS | 毫秒 (1/2/3 位) | 5 / 05 / 005 |
const fmt = new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
});
console.log(fmt.format(new Date())); // 2024/12/19 14:30:05
// 目前需 Polyfill
import { Temporal } from '@js-temporal/polyfill';
const dt = Temporal.Now.plainDateTimeISO();
console.log(dt.toString({ smallestUnit: 'millisecond' })); // 2024-12-19T14:30:05.123
format(date, 'yyyy-MM-dd HH:mm:ss'),模組化、Tree-shaking 友善。dayjs().format('YYYY-MM-DD HH:mm:ss'),API 兼容 Moment、體積 2KB。getMonth() 回傳 0-11,**記得 +1**。getDay() 回傳 0(日)-6(六),格式化常需自行對照表。new Date() 使用本地時區,傳輸建議用 ISO 字串 (toISOString()) 或 Timestamp。Date 與正則,可緩存編譯後的 RegExp 或使用庫函數。