上一篇談過 JavaScript 對 Date 物件的基本操作,本篇則聚焦在格式化,整理三種常見寫法以便對照挑選。
流傳最廣的版本。月、日、時、分、秒、季度可用 1 到 2 個占位符,年可用 1 到 4 個,毫秒只用 1 個占位符(實際為 1 至 3 位數字)。
// 對 Date 的擴充,將 Date 轉化為指定格式的 String
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
var 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() // 毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var 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;
};
var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
除了月日時間,還多支援 12 小時制 h、24 小時制 H 與星期 E,並依 E 的數量輸出「二」「周二」「星期二」三種長度。
/**
* 對 Date 的擴充,將 Date 轉化為指定格式的 String
* 月(M)、日(d)、12小時(h)、24小時(H)、分(m)、秒(s)、周(E)、季度(q) 可用 1-2 個占位符
* 年(y) 可用 1-4 個占位符,毫秒(S) 只用 1 個占位符
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss")==> 2009-03-10 星期二 08:09:04
*/
Date.prototype.pattern = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
var week = {
"0": "日", "1": "一", "2": "二", "3": "三",
"4": "四", "5": "五", "6": "六"
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ?
(RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
}
for (var 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;
};
var date = new Date();
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));
這版把「補零」抽成獨立的 zeroize 函式,再用一個大 regexp 一次比對所有占位符,命中後交給 switch 處理。除了基本年月日時分秒,還支援英文月名與星期全名、am/pm、時區等,是三者中表達力最強的。
Date.prototype.format = function (mask) {
var d = this;
var zeroize = function (value, length) {
if (!length) length = 2;
value = String(value);
for (var i = 0, zeros = ''; i < (length - value.length); i++) { zeros += '0'; }
return zeros + value;
};
return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g,
function ($0) {
switch ($0) {
case 'd': return d.getDate();
case 'dd': return zeroize(d.getDate());
case 'ddd': return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];
case 'dddd':return ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'][d.getDay()];
case 'M': return d.getMonth() + 1;
case 'MM': return zeroize(d.getMonth() + 1);
case 'MMM': return ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
case 'MMMM':return ['January','February','March','April','May','June','July',
'August','September','October','November','December'][d.getMonth()];
case 'yy': return String(d.getFullYear()).substr(2);
case 'yyyy':return d.getFullYear();
case 'h': return d.getHours() % 12 || 12;
case 'hh': return zeroize(d.getHours() % 12 || 12);
case 'H': return d.getHours();
case 'HH': return zeroize(d.getHours());
case 'm': return d.getMinutes();
case 'mm': return zeroize(d.getMinutes());
case 's': return d.getSeconds();
case 'ss': return zeroize(d.getSeconds());
case 'l': return zeroize(d.getMilliseconds(), 3);
case 'L': var m = d.getMilliseconds();
if (m > 99) m = Math.round(m / 10);
return zeroize(m);
case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
case 'Z': return d.toUTCString().match(/[A-Z]+$/);
default: return $0.substr(1, $0.length - 2); // 去掉包住字面文字的引號
}
});
};
三種寫法的取捨很直接:只要中文格式的年月日時分秒,方法一最省事;需要星期或 12 小時制,方法二更合適;要輸出英文月名、上下午標記或時區,方法三最完整。另外提醒,直接擴充 Date.prototype 在多人協作或引入第三方函式庫時容易撞名,建議改用解構式寫法 const formatDate = (date, mask) => {...},或直接使用 Intl.DateTimeFormat。