近期專案的部分功能正在重構,前端幾乎推翻了原本的設計。因為這個模組的核心就是時間控制,會大量操作 Date 物件,但 JS 原生的 Date 方法實在太少,算個「三天後」、「下個月」都要自己動手換算,實在不便。
長期寫 C# 的關係,思維一直被 DateTime 影響著——它的加減運算相當直覺。於是便參考 C# 的設計,為 JS 的 Date 擴充了 prototype。
// 將指定的毫秒數加到這個實例上
Date.prototype.addMilliseconds = function (value) {
this.setMilliseconds(this.getMilliseconds() + value);
return this;
};
// 將指定的秒數加到這個實例上
Date.prototype.addSeconds = function (value) {
this.setSeconds(this.getSeconds() + value);
return this;
};
// 將指定的分鐘數加到這個實例上
Date.prototype.addMinutes = function (value) {
this.setMinutes(this.getMinutes() + value);
return this;
};
// 將指定的小時數加到這個實例上
Date.prototype.addHours = function (value) {
this.setHours(this.getHours() + value);
return this;
};
// 將指定的天數加到這個實例上
Date.prototype.addDays = function (value) {
this.setDate(this.getDate() + value);
return this;
};
// 將指定的週數加到這個實例上
Date.prototype.addWeeks = function (value) {
return this.addDays(value * 7);
};
// 將指定的月份數加到這個實例上
Date.prototype.addMonths = function (value) {
this.setMonth(this.getMonth() + value);
return this;
};
// 將指定的年份數加到這個實例上
Date.prototype.addYears = function (value) {
this.setFullYear(this.getFullYear() + value);
return this;
};
// 格式化日期,例如 format("yyyy-MM-dd hh:mm:ss")
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 date = new Date();
date.addHours(1);
date.addYears(2);
document.write(date.format('yyyy-MM-dd hh:mm:ss'));
這裡有兩個細節值得說明。
第一,所有 add 方法都回傳 this,因此能串成鏈式呼叫:new Date().addDays(3).addHours(8)。不過要注意這些方法都是直接改動原物件(mutate),若需要保留原值,得先複製一份再運算。
第二,靠 setDate/setMonth 做加減之所以可靠,是因為 Date 物件內部會自動處理進位——1 月 31 日加一天會變成 2 月 1 日(閏年還會自動判斷)。但反过来,1 月 31 日加一個月會得到 3 月 3 日而非 2 月底,這是 JS 的原生行為,也是很多「日期加減」bug 的來源,使用時要留意。
另外,擴充內建物件的 prototype 在大型專案中並不是好習慣:一旦名稱與其他函式庫撞車,就會出現難以追蹤的錯誤。若要重來一次,我會把這些方法寫成獨立的工具函式(addDays(date, 3)),或直接採用 date-fns、Day.js 這類專門的日期函式庫。