js/jquery如何解析时间戳为指定格式

clipboard.png

不会解析时间,百度了很多都方法都是报错的

clipboard.png

我想转成yyyy-MM-dd HH:mm:ss格式的

阅读 3k
1 个回答

用库,date-fns 或者 moment

或者,这里有一段老代码,直接扩展 Date 对象的

Date.prototype.format = function(format = "yyyy-MM-dd") {
    var o = {
        //month 
        "M+": this.getMonth() + 1,
        // day  + 1
        "d+": this.getDate(),
        // hour (24小时)
        "H+": this.getHours(),
        // 小时(12小时)
        "h+": this.getHours() % 12,
        // minute 
        "m+": this.getMinutes(),
        // second 
        "s+": this.getSeconds(),
        // quarter 
        "q+": Math.floor((this.getMonth() + 3) / 3),
        // millisecond 
        "S": this.getMilliseconds()
    };

    if (/(y+)/i.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;
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题