萬盛學電腦網

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

JavaScript 日期格式化擴展:Date.prototype.format 實現詳解

原生 Date 缺乏靈活的格式化輸出,擴展 Date.prototype.format 可支援 YYYY-MM-DD hh:mm:ss 等任意模板,極大提升開發效率。

核心代碼

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()    // 毫秒
    };

    // 年份特殊處理:YYYY / YY
    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;
};

// 使用示例
console.log(new Date().format('YYYY-MM-dd hh:mm:ss.S')); // 2024-05-18 14:30:05.123
console.log(new Date().format('YYYY年M月d日'));           // 2024年5月18日

設計亮點

  • 正則動態替換:利用 RegExp.$1 捕獲模板中的佔位符長度,決定是否補零。
  • 擴展性強:只需在 o 對象添加鍵值即可支援新格式(如週 W)。
  • 零依賴:純原生 JS,無需 Moment.js、date-fns 等庫,適合輕量級項目。

注意事項

修改內建原型在大型團隊項目中可能引發命名衝突,建議封裝為獨立工具函數 formatDate(date, fmt) 或使用 ES Module 導出,避免污染全局 Date。

copyright © 萬盛學電腦網 all rights reserved