萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得當前日期與相對日期(前七天、昨天、明天)

核心工具函式

/**
 * 日期格式化擴充
 * 支援 yyyy, MM, dd, hh, mm, ss, q(季), S(毫秒)
 */
Date.prototype.format = function(fmt) {
    const o = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        '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 (const 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;
};

/**
 * 取得相對日期
 * @param {number} dayOffset - 偏移天數:0=今天, -1=明天, 1=昨天, 7=一週前, -7=一週後
 * @param {string} fmt - 輸出格式,預設 'yyyy-MM-dd'
 * @returns {string} 格式化日期字串
 */
function getRelativeDate(dayOffset = 0, fmt = 'yyyy-MM-dd') {
    const base = new Date();
    const target = new Date(base.getTime() + dayOffset * 24 * 60 * 60 * 1000);
    return target.format(fmt);
}

// 常用快捷函式
const today = () => getRelativeDate(0);
const yesterday = () => getRelativeDate(1);
const tomorrow = () => getRelativeDate(-1);
const weekAgo = () => getRelativeDate(7);
const weekLater = () => getRelativeDate(-7);

使用範例

<script>
// 直接輸出
document.write('今天:' + today());
document.write('<br>昨天:' + yesterday());
document.write('<br>明天:' + tomorrow());
document.write('<br>7天前:' + weekAgo());
document.write('<br>7天後:' + weekLater());

// 自訂格式
console.log(getRelativeDate(3, 'yyyy年MM月dd日')); // 3天後
console.log(getRelativeDate(-10, 'MM/dd/yyyy'));   // 10天前美式格式
</script>

現代替代方案:Intl.DateTimeFormat(無需擴充原型)

function formatDate(date, locale = 'zh-TW', options = {year:'numeric', month:'2-digit', day:'2-digit'}) {
    return new Intl.DateTimeFormat(locale, options).format(date);
}

function getRelativeDateModern(offsetDays, locale = 'zh-TW') {
    const d = new Date();
    d.setDate(d.getDate() + offsetDays);
    return formatDate(d, locale);
}

console.log(getRelativeDateModern(0));   // 2024/12/25
console.log(getRelativeDateModern(-7));  // 2024/12/18

優點:不汙染原型、內建多國語系、效能佳。
缺點:格式客製化彈性較低(無毫秒、季度等)。

常見陷阱

  • 月份從 0 開始:getMonth() 回傳 0-11,顯示時需 +1。
  • 夏令時間:跨 DST 邊界時 24*60*60*1000 可能不準,嚴謹場景請用 date.setDate(date.getDate() + offset) 讓瀏覽器自動處理。
  • 時區:new Date() 使用瀏覽器本地時區,伺服器端請用 UTC 方法(getUTCDate() 等)。

進階:取得「本週一」或「本月第一天」

function getWeekStart(date = new Date()) { // 週一為起始
    const d = new Date(date);
    const day = d.getDay(); // 0=週日
    const diff = d.getDate() - day + (day === 0 ? -6 : 1);
    d.setDate(diff);
    d.setHours(0,0,0,0);
    return d;
}

function getMonthStart(date = new Date()) {
    const d = new Date(date);
    d.setDate(1);
    d.setHours(0,0,0,0);
    return d;
}
copyright © 萬盛學電腦網 all rights reserved