JS时间格式转换 format函数

守給你的承諾、 提交于 2020-01-02 08:55:21

时间格式转换 format函数

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
                RegExp.$1, (RegExp.$1.length == 1)?(o[k]):
                (("00" + o[k]).substr(("" + o[k]).length))
            );
    return fmt;
}
let time1 = 1218154088000;
let time2 = '2015/11/11 00:00:00'

console.log( new Date(time1).format("yyyy-MM-dd hh:mm:ss") ) 
// 打印结果: 2008-08-08 08:08:08
console.log(new Date(time2).format("yyyy-^-^-MM-^-^-dd hh:-x-x-:mm:-x-x-:ss")) 
// 打印结果:  2015-^-^-11-^-^-11 00:-x-x-:00:-x-x-:00
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!