專案裡的日期處理往往不是「new Date()」這麼單純,而是要驗證使用者輸入、格式化輸出、判斷閏年、計算兩個日期相差幾天。以下把這些高頻需求整理成一組可直接擴充到 Date 上的工具函式。
· Date.isValiDate:日期合法性驗證
· Date.isValiTime:時間合法性驗證
· Date.isValiDateTime:日期與時間合法性驗證
· Date.prototype.isLeapYear:判斷是否為閏年
· Date.prototype.format:日期格式化
· Date.stringToDate:字串轉日期物件
· Date.daysBetween:計算兩個日期相差的天數
· Date.prototype.dateAdd:日期加減運算(支援負數)
· Date.prototype.dateDiff:比較兩個日期在同一單位上的差值
· Date.prototype.toArray:把日期拆成 [年, 月, 日, 時, 分, 秒]
· Date.prototype.datePart:取得單一日期欄位
傳統做法是用一整串正則表達式硬比對,既長又難維護。更穩健的思路是「先解析,再回頭比對」:把字串拆成年月日,交給 Date 建立物件,若日期被自動進位(例如 2 月 30 日變成 3 月 2 日),就代表輸入不合法。
/**
* 判斷 dateStr 是否符合 formatStr 指定的格式
* @param {String} dateStr 必填,日期字串
* @param {String} formatStr 選填,支援 yyyy-MM-dd(預設)、yyyy/MM/dd、MM-dd-yyyy、MM/dd/yyyy
* @returns {Boolean}
*/
Date.isValiDate = function (dateStr, formatStr) {
if (!dateStr) return false;
var format = formatStr || 'yyyy-MM-dd';
var parts = String(dateStr).split(/[-\/]/);
if (parts.length !== 3) return false;
var y, m, d;
if (/^yyyy/i.test(format)) {
y = Number(parts[0]); m = Number(parts[1]); d = Number(parts[2]);
} else {
m = Number(parts[0]); d = Number(parts[1]); y = Number(parts[2]);
}
if (!isFinite(y) || !isFinite(m) || !isFinite(d)) return false;
var date = new Date(y, m - 1, d);
return date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d;
};
alert(Date.isValiDate('2016-02-29', 'yyyy-MM-dd')); // true(閏年)
alert(Date.isValiDate('2015-02-29', 'yyyy-MM-dd')); // false(平年)
/**
* 判斷 timeStr 是否符合 hh:mm:ss 一類的時間格式
*/
Date.isValiTime = function (timeStr, formatStr) {
if (!timeStr) return false;
var format = formatStr || 'hh:mm:ss';
var sep = format.charAt(2); // ':'、'-' 或 '/'
var parts = String(timeStr).split(sep);
if (parts.length !== 3) return false;
var h = Number(parts[0]), m = Number(parts[1]), s = Number(parts[2]);
return h >= 0 && h <= 23 && m >= 0 && m <= 59 && s >= 0 && s <= 59;
};
alert(Date.isValiTime('23:59:59', 'hh:mm:ss')); // true
alert(Date.isValiTime('24:68:89', 'hh:mm:ss')); // false
Date.isValiDateTime = function (dateTimeStr) {
var parts = String(dateTimeStr).trim().split(/\s+/);
if (parts.length !== 2) return false;
return Date.isValiDate(parts[0], 'yyyy-MM-dd') && Date.isValiTime(parts[1], 'hh:mm:ss');
};
規則是「四年一閏,百年不閏,四百年再閏」。
Date.prototype.isLeapYear = function () {
var y = this.getFullYear();
return y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
};
約定:YYYY/yyyy/YY/yy 年、MM/M 月、W/w 星期、dd/DD/d/D 日、hh/HH/h/H 時、mm/m 分、ss/SS/s/S 秒、iii 毫秒。
Date.prototype.format = function (formatStr) {
var str = formatStr || 'yyyy-MM-dd hh:mm:ss';
var week = ['日', '一', '二', '三', '四', '五', '六'];
var pad = function (n) { return n < 10 ? '0' + n : '' + n; };
var map = {
yyyy: this.getFullYear(), yy: pad(this.getFullYear() % 100),
MM: pad(this.getMonth() + 1), M: this.getMonth() + 1,
W: week[this.getDay()], w: week[this.getDay()],
dd: pad(this.getDate()), d: this.getDate(),
HH: pad(this.getHours()), h: this.getHours(),
mm: pad(this.getMinutes()), m: this.getMinutes(),
ss: pad(this.getSeconds()), s: this.getSeconds(),
iii: ('00' + this.getMilliseconds()).slice(-3)
};
// 長的寫法必須排在前面,避免 yyyy 被 yy 搶先替換
return str.replace(/yyyy|yy|MM|M|dd|d|HH|h|mm|m|ss|s|iii|W|w/g, function (key) {
return map[key];
});
};
alert(new Date(2016, 4, 10, 9, 5, 3).format()); // 2016-05-10 09:05:03
不同瀏覽器對 Date.parse() 支援的格式不一,因此實務上通常先驗證格式、再交給 parse 處理。
Date.stringToDate = function (dateStr) {
if (!dateStr) return null;
var formats = ['yyyy/MM/dd', 'MM/dd/yyyy', 'yyyy-MM-dd'];
for (var i = 0; i < formats.length; i++) {
if (Date.isValiDate(dateStr, formats[i])) {
return new Date(Date.parse(dateStr.replace(/\//g, '-')));
}
}
return null;
};
Date.daysBetween = function (dateOne, dateTwo) {
if (!(dateOne instanceof Date) || !(dateTwo instanceof Date)) return 0;
var ONE_DAY = 24 * 60 * 60 * 1000;
return Math.round(Math.abs(dateOne.getTime() - dateTwo.getTime()) / ONE_DAY);
};
這裡用 Math.round 而不是 Math.floor,是為了避開日光節約時間造成的 23 小時或 25 小時,若直接無條件捨去會少算一天。
num 為正數是往後加、負數是往前減;field 指定作用在哪個單位上,預設為日。
Date.prototype.dateAdd = function (num, field) {
if (!num || isNaN(num) || Number(num) === 0) return this;
var ONE_SECOND = 1000, ONE_MINUTE = 60 * ONE_SECOND, ONE_HOUR = 60 * ONE_MINUTE,
ONE_DAY = 24 * ONE_HOUR, ONE_WEEK = 7 * ONE_DAY;
field = field || 'd';
switch (field) {
case 'Y': case 'y':
return new Date(this.getFullYear() + Number(num), this.getMonth(), this.getDate(),
this.getHours(), this.getMinutes(), this.getSeconds());
case 'Q': case 'q':
return new Date(this.getFullYear(), this.getMonth() + Number(num) * 3, this.getDate(),
this.getHours(), this.getMinutes(), this.getSeconds());
case 'M':
return new Date(this.getFullYear(), this.getMonth() + Number(num), this.getDate(),
this.getHours(), this.getMinutes(), this.getSeconds());
case 'W': case 'w': return new Date(+this + ONE_WEEK * num);
case 'D': case 'd': return new Date(+this + ONE_DAY * num);
case 'H': case 'h': return new Date(+this + ONE_HOUR * num);
case 'm': return new Date(+this + ONE_MINUTE * num);
case 'S': case 's': return new Date(+this + ONE_SECOND * num);
default: return this;
}
};
注意「加一個月」用毫秒換算會出錯(1 月 31 日加一個月不能等於 28 天後),所以年、季、月都改用建構函式重新組合,只有週以下的單位才用毫秒位移。
Date.prototype.dateDiff = function (dtEnd, field) {
if (!(dtEnd instanceof Date)) return 0;
var dtStart = this;
var diff = dtEnd - dtStart; // 毫秒差
field = field || 'd';
switch (field) {
case 'Y': case 'y': return dtEnd.getFullYear() - dtStart.getFullYear();
case 'M':
return (dtEnd.getFullYear() - dtStart.getFullYear()) * 12 + (dtEnd.getMonth() - dtStart.getMonth());
case 'W': case 'w': return parseInt(diff / (7 * 24 * 3600 * 1000));
case 'D': case 'd': return parseInt(diff / (24 * 3600 * 1000));
case 'H': case 'h': return parseInt(diff / (3600 * 1000));
case 'm': return parseInt(diff / (60 * 1000));
case 'S': case 's': return parseInt(diff / 1000);
default: return 0;
}
};
Date.prototype.toArray = function () {
return [this.getFullYear(), this.getMonth() + 1, this.getDate(),
this.getHours(), this.getMinutes(), this.getSeconds()];
};
Date.prototype.datePart = function (field) {
var week = ['日', '一', '二', '三', '四', '五', '六'];
switch (field || 'd') {
case 'Y': case 'y': return this.getFullYear();
case 'M': return this.getMonth() + 1;
case 'W': case 'w': return week[this.getDay()];
case 'H': case 'h': return this.getHours();
case 'm': return this.getMinutes();
case 's': return this.getSeconds();
default: return this.getDate();
}
};
直接擴充原生 prototype 雖然方便,但在多人協作或引入第三方函式庫時容易撞名,目前較推薦寫成獨立工具模組(例如 const dateUtil = { ... })再以 import 使用。另外,日期計算涉及商業邏輯時,建議搭配 Day.js、date-fns 或 Temporal 這類經過充分測試的實作,避免自己處理時區與閏秒的邊界情況。