日期運算最惱人的地方在於「跨月、跨年、閏年」都要自己處理。其實只要善用 Date 物件的毫秒值,加減天數就是一次乘法;而「某月有幾天」這類問題,也有很漂亮的解法。
/* 取得月份 */
function getMonths(dateday) {
return new Date(dateday).getMonth() + 1;
}
/* 取得年份 */
function getYears(dateday) {
return new Date(dateday).getFullYear();
}
/* 取得當月天數:把日期設為 0,就會回到上個月的最後一天 */
function getCountDays(dateday) {
var curDate = new Date(dateday);
curDate.setMonth(curDate.getMonth() + 1); // 先跳下個月
curDate.setDate(0); // 再退回「第 0 天」
return curDate.getDate();
}
setDate(0) 這個技巧值得記住:JavaScript 的日期會自動正規化,指定「本月第 0 天」等於「上個月的最後一天」,一行就解決了大小月與閏年判斷。
/* 取得 day 的昨天,預設 1 天,預設不輸出時間 */
function getBeforeDay(day, amount, isShortTime) {
if (Date.parse(day) != Date.parse(day)) return false; // 日期不合法
var days = new Date(new Date(day) - 1000 * 60 * 60 * 24);
if (amount) {
var number = parseInt(amount, 10);
if (number && number > 0 && !isNaN(number)) {
days = new Date(new Date(day) - 1000 * 60 * 60 * 24 * number);
}
}
return dateFormat(days, isShortTime);
}
/* 取得 day 的明天,預設 1 天 */
function getAfterDay(day, amount, isShortTime) {
if (Date.parse(day) != Date.parse(day)) return false;
var v = new Date(day).valueOf();
var days = new Date(v + 86400000);
if (amount) {
var number = parseInt(amount, 10);
if (number && number > 0 && !isNaN(number)) {
days = new Date(v + 86400000 * number);
}
}
return dateFormat(days, isShortTime);
}
/* 格式化輸出 */
function dateFormat(day, isShortTime) {
if (Date.parse(day) != Date.parse(day)) return false;
var days = new Date(day);
var y = days.getFullYear();
var m = days.getMonth() + 1;
var d = days.getDate();
if (isShortTime === true) {
var h = days.getHours() < 10 ? "0" + days.getHours() : days.getHours();
var mi = days.getMinutes() < 10 ? "0" + days.getMinutes() : days.getMinutes();
var s = days.getSeconds() < 10 ? "0" + days.getSeconds() : days.getSeconds();
return y + "-" + m + "-" + d + " " + h + ":" + mi + ":" + s;
}
return y + "-" + m + "-" + d;
}
注意 Date.parse(day) != Date.parse(day) 這個寫法:NaN 與任何值比較(包括自己)都會是 false,因此這其實是「NaN 檢測」的老技巧。今天更清楚的寫法是 isNaN(d.getTime())。
var DAY = 24 * 60 * 60 * 1000;
// 前後 N 天
function shift(date, n) {
return new Date(new Date(date).getTime() + n * DAY);
}
// 當月天數
function daysInMonth(date) {
var d = new Date(date);
return new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
}
// 格式化
function fmt(date, withTime) {
var d = new Date(date);
var p = n => String(n).padStart(2, '0');
var s = d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate());
return withTime ? s + " " + p(d.getHours()) + ":" + p(d.getMinutes()) + ":" + p(d.getSeconds()) : s;
}
shift('2024-03-05', -1); // 2024-03-04
daysInMonth('2024-02-10'); // 29(閏年)
+ 86400000 可能得到「同一天但時間差一小時」的結果。若只在意日期,改用 setDate(d.getDate() + n) 更安全。new Date("2024-01-01") 依 ECMAScript 規範是 UTC,而 new Date("2024/01/01") 是本地時間,兩者在東八區會差 8 小時。這是時區 bug 的常見來源。"" + m 不會補零,2024-1-5 與 2024-01-05 混用會讓字串排序失效。請用 padStart(2, '0')。