js格式化时间函数

js格式化时间函数

函数出处已经无从追溯,作为收藏,方便以后用。

函数:直接粘贴复制就可以用

Date.prototype.format = function (format) {
    
    
    var date = {
    
    
        "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+)/i.test(format)) {
    
    
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
    
    
        if (new RegExp("(" + k + ")").test(format)) {
    
    
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

用法:

function test(){
    
    
  var myDate = new Date();
  var nowStr = myDate.format("yyyy-MM-dd hh:mm:ss");
}

效果:

2021-11-05 21:14:14

Guess you like

Origin blog.csdn.net/huangqiang80/article/details/121170895