DIV CSS 佈局教程網

用 JS 擴充 Date.prototype 實作靈活的日期格式化
編輯:關於JavaScript     

JavaScript 原生的日期格式化能力相當陽春,想輸出 2026-08-26 21:23:00 得自己拼半天。實務上常見的解法是擴充 Date.prototype,加上一個 format 方法,之後任何日期物件都能直接呼叫。

程式碼

/**
 * 時間物件格式化
 * eg: format = "YYYY-MM-dd hh:mm:ss"
 */
Date.prototype.format = function(format) {
    var o = {
        "M+": this.getMonth() + 1,                                  // month
        "d+": this.getDate(),                                       // day
        "h+": this.getHours(),                                      // hour
        "m+": this.getMinutes(),                                    // minute
        "s+": this.getSeconds(),                                    // second
        "q+": Math.floor((this.getMonth() + 3) / 3),                // quarter
        "S":  this.getMilliseconds()                                // millisecond
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k]
                                      : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

用法

var d = new Date();

d.format("YYYY-MM-dd hh:mm:ss");   // 2026-08-26 21:23:00
d.format("YYYY年MM月dd日");         // 2026年08月26日
d.format("M/d/yy");                // 8/26/26
d.format("hh:mm");                 // 21:23
d.format("q季度");                  // 3季度

設計解析

格式符號:YYYY 年、MM 月、dd 日、hh 時、mm 分、ss 秒、q 季、S 毫秒。注意月份用大寫 M、分鐘用小寫 m,這與 Java 的 SimpleDateFormat 慣例一致。

年份處理。(getFullYear() + "").substr(4 - RegExp.$1.length) 這行的意思是:從四位數年份的字串中,取後 YYYY 的長度那麼多字元。YYYY 取 4 位、YY 取後 2 位。寫得雖然精簡,但可讀性偏低。

補零邏輯。("00" + o[k]).substr(("" + o[k]).length) 透過「前面補兩個 0,再從原字串長度處切」的方式達到補到兩位數的效果。若格式符只有一個字元(M、d)就用原值不補零,兩個字元(MM、dd)才補零。

季度的算法。Math.floor((month + 3) / 3):month 從 0 起算,所以 0 月(一月)得 (0+3)/3 = 1,2 月(三月)得 5/3 取整 = 1,3 月(四月)得 2,以此類推,結果正確。

這個實作可以改進的地方

用 RegExp.$1 是舊習慣。RegExp.$n 這種全域屬性在 strict mode 下不可用,也不符合現代寫法。改用 format.replace(/(y+)/, ...) 並在回呼中取參數會清楚得多。

每次迴圈都 new RegExp 效率不佳,可以先建好對照表。

修改內建 prototype 有風險。若頁面載入的第三方函式庫也擴充了 Date.prototype.format,就會互相覆蓋。較穩妥的做法是寫成獨立函式。

現代寫法

現在有標準 API 可用,不必自己造輪子:

var d = new Date();

// 萬用寫法
new Intl.DateTimeFormat('zh-TW', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
}).format(d);
// 2026/08/26 21:23:00

// 自訂格式用 toLocaleString
d.toLocaleDateString('zh-TW');   // 2026/8/26
d.toLocaleTimeString('zh-TW');   // 下午9:23:00

// 要完整控制格式,用 Intl.DateTimeFormat 的 formatToParts
new Intl.DateTimeFormat('zh-TW', { year:'numeric', month:'2-digit' })
    .formatToParts(d)
    .map(p => p.value).join('');

若專案需要豐富的格式符號(YYYY-MM-DD HH:mm:ss.SSS、相對時間、時區轉換),建議直接用 Day.js 或 date-fns 這類輕量函式庫,而不是自己維護格式字串。

另外提醒一個常見誤解:範例中的 h 對應 getHours(),是 24 小時制。若需要 12 小時制搭配 AM/PM,得另外處理,而 Intl.DateTimeFormat 的 hour12: true 已經幫你做完了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved