美文网首页
关于js时间显示格式的通用处理方法

关于js时间显示格式的通用处理方法

作者: chic_wx | 来源:发表于2022-12-02 23:06 被阅读0次

最近写前端页面总是会遇到与时间显示相关的需求
比如:

2022-12-02 22:00:00
2022.12.02 22:00:00
2022-12-02
2022.12.02
22:00:00

一般来说这些时间的标准传输格式为时间戳,所以封装一个方法如下

//filename global.js
Date.prototype.format = function(format) {
    /*
     * eg:format="YYYY-MM-dd hh:mm:ss";
     * new Date().format("yyyy.MM.dd");

     */
    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;
}

使用示例
new Date().format("yyyy-MM-dd hh:mm:ss");
2022-12-02 22:00:00

new Date().format("yyyy.MM.dd hh:mm:ss");
2022.12.02 22:00:00

new Date().format("yyyy-MM-dd");
2022-12-02

new Date().format("yyyy.MM.dd");
2022.12.02

new Date().format('hh:mm:ss')
22:00:00

new Date(1669992855111).format('yyyy-MM-dd hh:mm:ss')
2022-12-02 22:54:15

在H5、小程序中都可以使用,比如在uniapp的main.js文件中就可以引用上面的global.js,这样全局即可使用

//filename main.js
require('global.js');

相关文章

网友评论

      本文标题:关于js时间显示格式的通用处理方法

      本文链接:https://www.haomeiwen.com/subject/iouyfdtx.html