原生 Date 物件能用,但方法命名零散、又缺乏「回傳新物件而非改動自己」的概念。以下這套 DateTime 類別刻意模仿 .NET 的 API 設計,讓日期運算可以像 d.AddDays(3).AddMonths(1) 這樣串起來寫。
所有 Add 系列方法都不會改動原物件,而是先 Clone() 一份再運算,最後回傳新物件。這是它與原生 Date 最關鍵的差異,也是能安全串接的前提。
// 表示時間上的一刻,通常以日期和當天的時間表示。
function DateTime(year, month, day, hour, min, sec, millisec) {
var d = new Date();
if (year || year == 0) d.setFullYear(year);
if (month || month == 0) d.setMonth(month - 1); // 月份從 1 起算
if (day || day == 0) d.setDate(day);
if (hour || hour == 0) d.setHours(hour);
if (min || min == 0) d.setMinutes(min);
if (sec || sec == 0) d.setSeconds(sec);
if (millisec || millisec == 0) d.setMilliseconds(millisec);
// 將指定的天數加到此實例的值上
this.AddDays = function(value) {
if (!ValidateAddMethodParam(value)) return null;
var result = this.Clone();
result.GetValue().setDate(result.GetDay() + value);
return result;
};
// 其餘 AddHours / AddMinutes / AddSeconds / AddMonths / AddYears
// 皆為相同結構,只是置換對應的 setter 與 getter
// ...
// 與另一個日期比較:大於回傳 1、小於回傳 -1、相等回傳 0
this.CompareTo = function(other) {
var internalTicks = other.getTime();
var num2 = d.getTime();
if (num2 > internalTicks) return 1;
if (num2 < internalTicks) return -1;
return 0;
};
// 回傳一個數值相同的新 DateTime 物件
this.Clone = function() {
return new DateTime(
this.GetYear(), this.GetMonth(), this.GetDay(),
this.GetHour(), this.GetMinute(), this.GetSecond(),
this.GetMillisecond());
};
this.Equals = function(other) { return this.CompareTo(other) == 0; };
this.GetDate = function() { return new DateTime(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0); };
this.GetDay = function() { return d.getDate(); };
this.GetDayOfWeek = function() { return d.getDay(); };
this.GetHour = function() { return d.getHours(); };
this.GetMinute = function() { return d.getMinutes(); };
this.GetMillisecond = function() { return d.getMilliseconds(); };
this.GetMonth = function() { return d.getMonth() + 1; };
this.GetSecond = function() { return d.getSeconds(); };
this.GetValue = function() { return d; };
this.GetYear = function() { return d.getFullYear(); };
this.getTime = function() { return d.getTime(); };
// 下個月一日
this.GetNextMonthFirstDay = function() {
var result = new DateTime(this.GetYear(), this.GetMonth(), 1, 0, 0, 0, 0);
return result.AddMonths(1);
};
// 下一個周日
this.GetNextWeekFirstDay = function() {
var result = this.GetDate();
return result.AddDays(7 - result.GetDayOfWeek());
};
// 下一年元旦
this.GetNextYearFirstDay = function() {
return new DateTime(this.GetYear() + 1, 1, 1, 0, 0, 0, 0);
};
// 格式化輸出
this.ToShortDateString = function() {
return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
};
this.ToShortTimeString = function() {
return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
};
this.ToString = function(format) {
return this.ToShortDateString() + " " + this.ToShortTimeString();
};
// 驗證 Add 系列方法的參數是否合法
function ValidateAddMethodParam(param) {
if (typeof(param) != "number") return false;
return true;
}
}
除了實例方法,類別本身也掛上了幾個實用的靜態成員:
// 比較兩個實例,回傳相對值
DateTime.Compare = function(d1, d2) { return d1.CompareTo(d2); };
// 回傳指定年月的天數
DateTime.DaysInMonth = function(year, month) {
if ((month < 1) || (month > 12)) return "月份[" + month + "]超出範圍";
var numArray = DateTime.IsLeapYear(year)
? DateTime.DaysToMonth366 : DateTime.DaysToMonth365;
return (numArray[month] - numArray[month - 1]);
};
// 判斷是否閏年
DateTime.IsLeapYear = function(year) {
if ((year < 1) || (year > 0x270f)) return "年份[" + year + "]超出範圍";
if ((year % 4) != 0) return false;
if ((year % 100) == 0) return ((year % 400) == 0);
return true;
};
// 解析字串為 DateTime,日期與時間可分別獨立擷取
DateTime.Parse = function(s) {
var result = new DateTime();
var value = result.GetValue();
value.setHours(0, 0, 0, 0);
var dateRex = /\b[1-2][0-9][0-9][0-9][-]\d{1,2}[-]\d{1,2}\b/i;
if (!dateRex.test(s)) return null;
var dateStr = s.match(dateRex)[0];
var dateParts = dateStr.split("-");
value.setFullYear(dateParts[0] - 0, dateParts[1] - 1, dateParts[2] - 0);
var timeRex = /\b\d{1,2}[:]\d{1,2}[:]\d{1,2}\b/i;
if (timeRex.test(s)) {
var timeParts = s.match(timeRex)[0].split(":");
value.setHours(timeParts[0] - 0, timeParts[1] - 0, timeParts[2] - 0);
}
return result;
};
// 當前日期時間
DateTime.Now = new DateTime();
// 今日 00:00:00
DateTime.Today = new DateTime(null, null, null, 0, 0, 0, 0);
// 靜態查表用的累計天數(十六進位寫法)
DateTime.DaysToMonth365 = [0, 0x1f, 0x3b, 90, 120, 0x97, 0xb5, 0xd4, 0xf3, 0x111, 0x130, 0x14e, 0x16d];
DateTime.DaysToMonth366 = [0, 0x1f, 60, 0x5b, 0x79, 0x98, 0xb6, 0xd5, 0xf4, 0x112, 0x131, 0x14f, 0x16e];
這兩組「累計天數表」是 DaysInMonth 的資料來源:用相鄰兩項相減,就能快速得到某個月的天數,閏年則改用 366 版本,閏年判斷與查表搭配得相當漂亮。
這套實作有兩個值得注意的地方:一是 DateTime.Now 與 DateTime.Today 是在腳本載入時就求值的靜態物件,並非每次存取都重新計算,長時間開著的頁面會拿到過期時間;二是 AddDays 內部用的是 GetDay()(回傳「月份的哪一天」)而非 GetDate(),在跨月情境下行為可能不如預期。
在今天的專案中,若只是要格式化日期,Intl.DateTimeFormat 或 date-fns、Day.js 這類現代函式庫會是更省心的選擇;但如果你想理解「如何設計一個不可變的日期型別」,這份實作仍是很值得讀的教材。