Questions about date conversion format in Js-Date().format()

One thing that makes bloggers bother brains: I don’t want to write by hand, but in the final method, I still write by hand, record it

When writing Js, there is a place where the date is used , and the requirement is the format of yyyy--MM--dd , so the format function is thought of

//Current time
 var Time = new Date().format("yyyy-MM-dd");
 
But at that time format was reported red, and later I learned that it is necessary to call the time function when the page loads js , the code is as follows:
$(function () {
    datatime();
    
});
//时间函数
function datatime(){
    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;
    }
}

Guess you like

Origin blog.csdn.net/My_SweetXue/article/details/113716095