日期處理是前端最常被低估的麻煩事。這份工具集透過擴充 Date.prototype,把格式化、日期運算、差值比較、合法性驗證等常用操作一次備齊,適合直接放進專案的工具檔裡。
Date.prototype.isLeapYear = function () {
var y = this.getFullYear();
return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
};
/**
* 格式化:yyyy 年、MM 月、dd 日、HH 時、mm 分、ss 秒、S 毫秒
* (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") // 2006-07-02 08:09:04.423
*/
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours() % 12 || 12,
"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.pattern = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours() % 12 || 12,
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S" : this.getMilliseconds()
};
var week = ["日", "一", "二", "三", "四", "五", "六"];
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
if (/(E+)/.test(fmt)) {
var len = RegExp.$1.length;
fmt = fmt.replace(RegExp.$1,
(len > 1 ? (len > 2 ? "星期" : "周") : "") + week[this.getDay()]);
}
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;
};
// (new Date()).pattern("yyyy-MM-dd EEE HH:mm:ss") // 2009-03-10 星期二 20:09:04
/**
* @param strInterval s 秒 / n 分 / h 時 / d 天 / w 周 / q 季 / m 月 / y 年
*/
Date.prototype.DateAdd = function (strInterval, number) {
var d = this;
switch (strInterval) {
case 's': return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds() + number);
case 'n': return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes() + number, d.getSeconds());
case 'h': return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + number, d.getMinutes(), d.getSeconds());
case 'd': return new Date(d.getFullYear(), d.getMonth(), d.getDate() + number, d.getHours(), d.getMinutes(), d.getSeconds());
case 'w': return new Date(d.getFullYear(), d.getMonth(), d.getDate() + number * 7, d.getHours(), d.getMinutes(), d.getSeconds());
case 'q': return new Date(d.getFullYear(), d.getMonth() + number * 3, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
case 'm': return new Date(d.getFullYear(), d.getMonth() + number, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
case 'y': return new Date(d.getFullYear() + number, d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
}
};
Date.prototype.DateDiff = function (strInterval, dtEnd) {
var dtStart = this;
if (typeof dtEnd == 'string') dtEnd = StringToDate(dtEnd);
switch (strInterval) {
case 's': return parseInt((dtEnd - dtStart) / 1000);
case 'n': return parseInt((dtEnd - dtStart) / 60000);
case 'h': return parseInt((dtEnd - dtStart) / 3600000);
case 'd': return parseInt((dtEnd - dtStart) / 86400000);
case 'w': return parseInt((dtEnd - dtStart) / (86400000 * 7));
case 'm': return (dtEnd.getMonth() + 1) + (dtEnd.getFullYear() - dtStart.getFullYear()) * 12 - (dtStart.getMonth() + 1);
case 'y': return dtEnd.getFullYear() - dtStart.getFullYear();
}
};
function StringToDate(DateStr) {
var converted = Date.parse(DateStr);
var myDate = new Date(converted);
if (isNaN(myDate)) {
var arys = DateStr.split('-');
myDate = new Date(arys[0], --arys[1], arys[2]);
}
return myDate;
}
// 格式須為 YYYY-MM-DD 或 YYYY/MM/DD
function IsValidDate(DateStr) {
var s = DateStr.replace(/(^\s+|\s+$)/g, '');
if (s == '') return true;
var rest = s.replace(/[\d]{4}[\-/]{1}[\d]{1,2}[\-/]{1}[\d]{1,2}/g, '');
if (rest != '') return false;
var t = new Date(s.replace(/\-/g, '/'));
var ar = s.split(/[-/:]/);
if (ar[0] != t.getFullYear() || ar[1] != t.getMonth() + 1 || ar[2] != t.getDate())
return false; // 例如 2 月 30 日這種被自動進位的假日期
return true;
}
// 格式須為 YYYY-MM-DD HH:MM:SS
function CheckDateTime(str) {
var r = str.match(/^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
if (r == null) return false;
var d = new Date(r[1], r[2] - 1, r[3], r[4], r[5], r[6]);
return d.getFullYear() == r[1] && d.getMonth() == r[2] - 1 && d.getDate() == r[3]
&& d.getHours() == r[4] && d.getMinutes() == r[5] && d.getSeconds() == r[6];
}
// 取得当月天數
Date.prototype.MaxDayOfDate = function () {
var d = this;
return new Date(d.getFullYear(), d.getMonth() + 2, 0).getDate();
};
// 拆成陣列 [年, 月(0-based), 日, 時, 分, 秒]
Date.prototype.toArray = function () {
return [this.getFullYear(), this.getMonth(), this.getDate(),
this.getHours(), this.getMinutes(), this.getSeconds()];
};
// 依 interval 取值:y 年 / m 月 / d 日 / w 星期 / h 時 / n 分 / s 秒
Date.prototype.DatePart = function (interval) {
var week = ['日', '一', '二', '三', '四', '五', '六'];
switch (interval) {
case 'y': return this.getFullYear();
case 'm': return this.getMonth() + 1;
case 'd': return this.getDate();
case 'w': return week[this.getDay()];
case 'h': return this.getHours();
case 'n': return this.getMinutes();
case 's': return this.getSeconds();
}
};
<input type="button" value="點擊查看" onclick="newdatetime()" />
<script type="text/javascript">
var nowtime = new Date();
function newdatetime() {
nowtime = nowtime.DateAdd("h", 35); // 加 35 小時
alert(nowtime.Format("yyyy-MM-dd HH:mm:ss"));
}
</script>
getMonth() 的地方都要 +1,這是新手最常犯的錯。Date.prototype.toString 會影響所有依賴預設字串(例如除錯輸出、第三方函式庫)的地方,建議另取一個方法名。DateUtil.format(d, fmt)。Intl.DateTimeFormat 做格式化(內建、支援多語系),複雜運算則交給 Day.js、date-fns 或 Temporal API,能避免時區與日光節約時間的隱形地雷。