Javascript中Date对象的格式化

很多语言中都带有日期的格式化函数,而Javascript中却没有提供类似的方法。
之前从某位前人的帖子中发现了下面的代码,感觉非常简洁,存留备用。

/**
* 时间对象的格式化;
*/
Date.prototype.format = function (format) {
    /*
       示例 
       var d=new Date();
       d.format("YYYY-MM-dd hh:mm:ss");
       结果:"2014-01-02 12:34:56"   
    */
    var 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(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;
}
原文地址:https://www.cnblogs.com/sheijianeixiaorui/p/3924730.html