Javascript擴展Date的prototype實現時間format函數


代碼:
Date.prototype.format = function(pattern) {
    /*初始化返回值字符串*/
    var returnValue = pattern;
    /*正則式pattern類型對象定義*/
    var format = {
        "y+": this.getFullYear(),
        "M+": this.getMonth()+1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "S": this.getMilliseconds(),
        "h+": (this.getHours()%12),
        "a": (this.getHours()/12) <= 1? "AM":"PM"
    };
    /*遍歷正則式pattern類型對象構建returnValue對象*/
    for(var key in format) {
        var regExp = new RegExp("("+key+")");
        if(regExp.test(returnValue)) {
            var zero = "";
            for(var i = 0; i < RegExp.$1.length; i++) { zero += "0"; }
            var replacement = RegExp.$1.length == 1? format[key]:(zero+format[key]).substring(((""+format[key]).length));
            returnValue = returnValue.replace(RegExp.$1, replacement);
        }
    }
    return returnValue;
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM