日期處理幾乎每個專案都會遇到,先把 Date 的取用方法整理清楚,再談格式化。
var myDate = new Date(); myDate.getYear(); // 取得當前年份(2 位) myDate.getFullYear(); // 取得完整年份(4 位) myDate.getMonth(); // 取得當前月份(0-11,0 代表 1 月) myDate.getDate(); // 取得當日(1-31) myDate.getDay(); // 取得星期幾(0-6,0 代表週日) myDate.getTime(); // 取得從 1970.1.1 起算的毫秒數 myDate.getHours(); // 當前小時(0-23) myDate.getMinutes(); // 當前分鐘(0-59) myDate.getSeconds(); // 當前秒數(0-59) myDate.getMilliseconds(); // 當前毫秒(0-999) myDate.toLocaleDateString(); // 當前日期 myDate.toLocaleTimeString(); // 當前時間 myDate.toLocaleString(); // 日期與時間
最需要注意的是 getMonth() 從 0 起算,這是最常見的++/-- 出錯來源;getYear() 回傳的值在不同瀏覽器上也不一致,一律改用 getFullYear()。
下面這個方法可以說是 Web 專案的常備工具:
Date.prototype.format = function (format)
{
var o = {
"M+" : this.getMonth() + 1, // month
"d+" : this.getDate(), // day
"h+" : this.getHours(), // hour
"m+" : this.getMinutes(), // minute
"s+" : this.getSeconds(), // second
"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
"S" : this.getMilliseconds() // millisecond
}
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;
}
宣告後即可使用:
var d = new Date().format('yyyy-MM-dd');
Date 物件本身有四個輸出為字串的內建方法:
1. toGMTString:以 GMT 格式顯示
2. toLocaleString:以本機作業系統格式顯示
3. toLocaleDateString:以本機格式顯示日期部分
4. toLocaleTimeString:以本機格式顯示時間部分
問題在於這些格式由環境決定,無法自訂。若需要指定格式,早期可以引入 JsJava 這類工具庫:
var df = new SimpleDateFormat(); // jsJava 1.0 需使用 DateFormat 物件
df.applyPattern("yyyy-MM-dd HH:mm:ss");
var date = new Date(2007, 3, 30, 10, 59, 51);
var str = df.format(date);
document.write(str); // 2007-04-30 10:59:51
其中的 pattern 沿用了 Java 日期格式化的約定,主要佔位符如下:
G Era designator AD y Year 1996; 96 M Month in year July; Jul; 07 w Week in year 27 W Week in month 2 D Day in year 189 d Day in month 10 F Day of week in month 2 E Day in week Tuesday; Tue a Am/pm marker PM H Hour in day (0-23) 0 k Hour in day (1-24) 24 K Hour in am/pm (0-11) 0 h Hour in am/pm (1-12) 12 m Minute in hour 30 s Second in minute 55 S Millisecond 978
新專案已不需要自己擴充 prototype。Intl.DateTimeFormat 是標準 API,能直接輸出本地化的日期字串,且效能經過高度優化:
new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit'
}).format(new Date()); // 2026/08/19
若只是要固定格式的字串,dayjs、date-fns 這類輕量函式庫也比自行維護 format 更省心。