最近要用到日期转为星期,以前的格式化只包含日期时间,故做了修改,发上来与君共享。

/// <summary>
/// 日期格式化
/// new Date().Format('yyyy-MM-dd hh:mm:ss S W w Q')
/// </summary>
Date.prototype.Format = function (fmt) {

    const week = "日一二三四五六";
    const o = {
        'y+': this.getFullYear(), // 年
        "M+": this.getMonth() + 1, // 月
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "S+": this.getMilliseconds(), // 毫秒
        "w+": this.getDay(), // 星期数值,1-6星期一至六,0星期天
        "W+": this.getDay(), // 星期汉字
        "Q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    };

    for (let k in o) {
        const regx = new RegExp("(" + k + ")");
        if (regx.test(fmt)) {
            const t = regx.exec(fmt)[1];
            fmt = fmt.replace(
                t,
                k === 'W+' ?
                    "星期" + week.substring(o[k], o[k] + 1) :
                    t.length == 1 ?
                        o[k] :  o[k].toString().padStart(t.length, '0')
            );
        }
    }

    return fmt;
};

使用

> new Date().Format("yyyy-MM-dd hh:mm:ss SSS WW w Q")
< '2023-07-28 14:20:03 060 星期五 5 3'

> new Date("2023-07-27 11:38:43:123").Format("yyyy-MM-dd hh:mm:ss S W w Q")
< '2023-07-27 11:38:43 123 星期四 4 3'

> new Date("2023-07-27 11:38:43:123").Format("yyyy-MM-dd W")
< '2023-07-27 星期四'
posted on 2023-07-28 14:28  Apull  阅读(30)  评论(0)    收藏  举报  来源