JS时间格式化添加星期和季度

博主因需将日期转为星期,对以往仅包含日期时间的格式化进行了修改,并分享出来。涉及到日期处理相关内容,与信息技术领域的开发应用相关。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/// <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 星期四'
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值