js时间格式化

代码附上

Date.prototype.format = function (fmt) {
    const o = {
        "y+": this.getFullYear(),
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "S+": this.getMilliseconds(),
        "q+": Math.floor(this.getMonth() / 3) + 1,
        "h+": (() => {
            const hour = this.getHours() % 12;
            return hour === 0 ? 12 : hour;
        })(),
        "E+": (() => {
            const week = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday" };
            return week[this.getDay() + ""];
        })(),
        /*
        "e+": (()=>{
            const week = {"0":"Sun","1":"Mon","2":"Tue","3":"Wed","4":"Thu","5":"Fri","6":"Sat"};
            return week[this.getDay()+""];
        })(),
        */
        "x1": (() => {
            const week = { "0": "周日", "1": "周一", "2": "周二", "3": "周三", "4": "周四", "5": "周五", "6": "周六" };
            return week[this.getDay() + ""];
        })(),
        "x2": (() => {
            const hour = ["凌晨", "早上", "下午", "晚上"];
            const h = this.getHours();
            if (h === 12) return "中午";
            return hour[parseInt(h / 6)];
        })(),
    };
    for (let k in o) {
        if (new RegExp("(" + k + ")", "g").test(fmt)) {
            const len = RegExp.$1.length;
            fmt = fmt.replace(RegExp.$1, len === 1 ? o[k] : ("00" + o[k]).substr(-len));
        }
    }
    return fmt;
};

使用方法和php的时间类相似 new Date().format('yyyy/MM/dd HH:mm:ss,x1,x2')

上面的代码将输出

"2019/08/09 14:33:08,周五,下午"