JavaScript 沒有 C# 那樣現成的 AddDays、AddMonths 方法,日期運算得自己攢。專案裡常見的需求是「這個日期往後推 N 個月」,看似簡單,實作時卻有個容易忽略的細節:閏年、大小月與月末溢出。
例如 1 月 31 日加一個月,如果直接 setMonth(1),結果會變成 3 月 3 日。下面的寫法用迴圈把多溢出來的天數扣回去,讓結果停在 2 月的合法日期上。
function dateToDate(date) {
var sDate = new Date();
if (typeof date == 'object' && typeof new Date().getMonth == "function") {
sDate = date;
} else if (typeof date == "string") {
var arr = date.split('-');
if (arr.length == 3) { sDate = new Date(arr[0] + '-' + arr[1] + '-' + arr[2]); }
}
return sDate;
}
function addMonth(date, num) {
num = parseInt(num);
var sDate = dateToDate(date);
var sYear = sDate.getFullYear();
var sMonth = sDate.getMonth() + 1;
var sDay = sDate.getDate();
var eYear = sYear;
var eMonth = sMonth + num;
var eDay = sDay;
while (eMonth > 12) { eYear++; eMonth -= 12; }
var eDate = new Date(eYear, eMonth - 1, eDay);
// 若溢出到下個月,逐日回退直到落在目標月份
while (eDate.getMonth() != eMonth - 1) {
eDay--;
eDate = new Date(eYear, eMonth - 1, eDay);
}
return eDate;
}
function calcDate() {
var d = document.getElementById('date').value;
var n = document.getElementById('num').value;
var eDate = addMonth(d, n);
document.getElementById('result').innerHTML =
eDate.getFullYear() + '-' + (eDate.getMonth() + 1) + '-' + eDate.getDate();
}
把常用運算掛到原型上,呼叫起來最直覺。這裡同時附上一個相當實用的格式化方法:
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;
};
Date.prototype.addDays = function (d) { this.setDate(this.getDate() + d); };
Date.prototype.addWeeks = function (w) { this.addDays(w * 7); };
Date.prototype.addMonths = function (m) {
var d = this.getDate();
this.setMonth(this.getMonth() + m);
if (this.getDate() < d) this.setDate(0); // 回退到上個月的最後一天
};
Date.prototype.addYears = function (y) {
var m = this.getMonth();
this.setFullYear(this.getFullYear() + y);
if (m < this.getMonth()) this.setDate(0);
};
如果你從 ASP/VBScript 世界遷移過來,這種介面會很熟悉,用 interval 字串指定單位:
function DateAdd(interval, number, date) {
switch (interval) {
case "y": date.setFullYear(date.getFullYear() + number); return date;
case "q": date.setMonth(date.getMonth() + number * 3); return date;
case "m": date.setMonth(date.getMonth() + number); return date;
case "w": date.setDate(date.getDate() + number * 7); return date;
case "d": date.setDate(date.getDate() + number); return date;
case "h": date.setHours(date.getHours() + number); return date;
case "n": date.setMinutes(date.getMinutes() + number); return date;
case "s": date.setSeconds(date.getSeconds() + number); return date;
default: date.setDate(date.getDate() + number); return date;
}
}
var now = new Date();
alert(DateAdd("d", 5, now).toLocaleDateString()); // 加五天
alert(DateAdd("m", 2, now).toLocaleDateString()); // 加兩個月
alert(DateAdd("y", 1, now).toLocaleDateString()); // 加一年
三種寫法各有適用場景:方法一邏輯最完整、適合直接搬進工具函式庫;方法二呼叫最順手,但要留意擴充原生原型可能與其他庫衝突;方法三勝在介面通用、單位涵蓋廣。值得一提的是,方法三的原始版本把「分」與「月」都寫成 "m",是個經典的 switch 遺漏,實用上建議把分鐘改成 "n" 以免永遠進不到那個分支。