在js中对时间类型格式化字符串

复制代码
Date.prototype.toString = function (format) {
    if (format == null) {
        format = "yyyy-MM-dd HH:mm:ss";
    }

    format = format.replace(/yyyy/g, this.getFullYear());
    format = format.replace(/yyy/g, this.getYear());
    format = format.replace(/yy/g, this.getFullYear().toString().slice(-2));

    if (format.indexOf('mi') >= 0) {
        format = format.replace(/mi/g, this.getMilliseconds().toString());
    }

    if (format.indexOf('M') >= 0) {
        var M = (this.getMonth() + 1).toString();
        format = format.replace(/MM/g, ("0" + M).slice(-2));
        format = format.replace(/M/g, M);
    }

    if (format.indexOf('ddd') >= 0) {
        var xq = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
        format = format.replace(/ddd/g, xq[this.getDay()]);
    }

    if (format.indexOf('d') >= 0) {
        var d = this.getDate().toString();
        format = format.replace(/dd/g, ("0" + d).slice(-2));
        format = format.replace(/d/g, d);
    }


    if (format.indexOf('h') >= 0 || format.indexOf('H') >= 0) {
        var h = this.getHours();
        format = format.replace(/HH/g, ("0" + h.toString()).slice(-2));
        format = format.replace(/H/g, h);
        h = h % 12;
        format = format.replace(/hh/g, ("0" + h.toString()).slice(-2));
        format = format.replace(/h/g, h);
    }

    if (format.indexOf('m') >= 0) {
        var m = this.getMinutes().toString();
        format = format.replace(/mm/g, ("0" + m).slice(-2));
        format = format.replace(/m/g, m);
    }

    if (format.indexOf('s') >= 0) {
        var s = this.getSeconds().toString();
        format = format.replace(/ss/g, ("0" + s).slice(-2));
        format = format.replace(/s/g, m);
    }



    return format;
}
复制代码

效果

代码段

https://code.csdn.net/snippets/76928

posted @   冰麟轻武  阅读(667)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示