JavaScript 原生的 Date 沒有 format() 方法,這是很多人詬病的痛點。要輸出「2013-10-17 12:00:00」這樣的字串,得自己拼。本文提供一套完整的格式化方案:先擴充原型,再包裝成幾個好用的工具函式。
做法是用一個對照表把格式字元(y、M、d、h、m、s、q、S)映射到對應數值,再用正則替換。連續兩個以上的格式字元會自動補零對齊。
//擴展Date的format方法
Date.prototype.format = function (format) {
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(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;
}
幾個細節:getMonth() 回傳 0–11,所以要 +1;q+ 是季度,用 (month + 3) / 3 取整數;補零的技巧是「前面湊兩個 0,再從尾巴切」——("00" + 9).substr(2) 得到 "09",而 ("00" + 12).substr(2) 得到 "12",剛好同時處理個位與十位。
有了底層的 format,就能往上包一層更好用的介面。
把 Date 物件轉字串,可選擇要不要帶時間:
/**
* 轉換日期對象為日期字符串
* @param date 日期對象
* @param isFull 是否為完整的日期數據,
* 為true時, 格式如"2000-03-05 01:05:04"
* 為false時, 格式如 "2000-03-05"
* @return 符合要求的日期字符串
*/
function getSmpFormatDate(date, isFull) {
var pattern = "";
if (isFull == true || isFull == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
} else {
pattern = "yyyy-MM-dd";
}
return getFormatDate(date, pattern);
}
直接取「現在」的格式化字串,是實務上最常用的一個:
/**
* 轉換當前日期對象為日期字符串
*/
function getSmpFormatNowDate(isFull) {
return getSmpFormatDate(new Date(), isFull);
}
把 13 位數的時間戳(long 值)轉成字串。後端傳來的時間幾乎都是這個形式,所以這兩個函式非常實用:
/**
* 轉換long值為日期字符串
* @param l long值
* @param isFull 是否為完整的日期數據
*/
function getSmpFormatDateByLong(l, isFull) {
return getSmpFormatDate(new Date(l), isFull);
}
/**
* 轉換long值為日期字符串
* @param l long值
* @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss
*/
function getFormatDateByLong(l, pattern) {
return getFormatDate(new Date(l), pattern);
}
最後是最通用的底層函式,兩個參數都可省略,會自動帶入「現在」與預設格式:
/**
* 轉換日期對象為日期字符串
* @param date 日期對象
* @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss
*/
function getFormatDate(date, pattern) {
if (date == undefined) {
date = new Date();
}
if (pattern == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
}
return date.format(pattern);
}
使用範例:
alert(getSmpFormatDate(new Date(1279849429000), true)); // 完整格式 alert(getSmpFormatDate(new Date(1279849429000), false)); // 只有日期 alert(getSmpFormatDateByLong(1279829423000, true)); alert(getFormatDateByLong(1279829423000, "yyyy-MM")); alert(getFormatDate(new Date(1279829423000), "yy-MM")); alert(getFormatDateByLong(1279849429000, "yyyy-MM hh:mm"));
值得注意的一個設計細節:isFull == undefined 時預設走完整格式。這種「不傳就給最完整的結果」的預設值策略,能減少呼叫端漏傳參數導致的錯誤。另外,直接改寫 Date.prototype 雖然方便,但在多人協作的大型專案中容易造成命名衝突,改成獨立工具函式(例如 dayjs 風格的 format(date, pattern))會更安全。