Date 是 JS 內建處理日期時間的物件,掌握幾個小技巧能省去引入重型日期庫。本文整理四個高頻實用場景。
// Date 建構子:月份 0-11,日傳 0 表示「上個月最後一天」
function getDaysInMonth(year, month) { // month: 1-12
return new Date(year, month, 0).getDate();
}
getDaysInMonth(2024, 2); // 29 (閏年)
getDaysInMonth(2023, 2); // 28
// 判斷閏年
function isLeapYear(year) {
return getDaysInMonth(year, 2) === 29;
}
var offsetMinutes = new Date().getTimezoneOffset(); // 台灣為 -480
var timezone = -offsetMinutes / 60; // 8 (東八區)
// 另一種:解析 toString() 回傳字串
// "Mon Jan 01 2024 00:00:00 GMT+0800 (台北標準時間)"
var tzStr = new Date().toString().match(/GMT([+-]\d+)/)[1]; // "+0800"
var start = performance.now(); // 高精度毫秒(微秒級)
// 或 Date.now() 僅毫秒級
doHeavyWork();
console.log('耗時:', performance.now() - start, 'ms');
建議使用 performance.now(),精度達微秒,且不受系統時間調整影響。
function deleteCookie(name) {
document.cookie = name + '=; expires=' + new Date(0).toUTCString() + '; path=/';
}
// new Date(0) = 1970-01-01T00:00:00.000Z
瀏覽器發現過期時間早於當前時間,即自動刪除該 Cookie。
Temporal 提案(Stage 3)未來將取代 Date,提供不可變、時區感知、更豐富的 APIDate 物件的 setter(setMonth 等易產生副作用)