DIV CSS 佈局教程網

JS 實現靈活日期格式化的小範例
編輯:JavaScript綜合知識     

日期格式化是前端開發中經常遇到的需求。以下分享一個相當靈活的寫法,只要擴充 Date 的原型,就能以自訂格式字串輸出日期。

完整程式碼:

/**
 * 時間物件的格式化
 * 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;
};

使用時只需呼叫 (new Date()).format("yyyy-MM-dd hh:mm:ss"),就能得到格式化後的字串。它的原理是先處理年份(y),再逐一比對月份、日、時、分、秒等欄位並替換;當格式字元為單個時輸出原值,為兩個時則自動補零對齊,非常貼心。

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