时间在程序中经常被用到,后台一般都是返回的毫秒数,这个时候就需要我们前端人员去格式化后再显示出正确的时间。下面是一个通用的方法:
首先,我们要拿到毫秒数
// 重写格式化时间函数,转成当地时间
Date.prototype.toLocaleString = function() {
// 补0 例如 2016-5-10 13:5:5 补完后为 2016-05-10 13:05:05
function addZero(num) {
if(num<10)
return "0" + num;
return num;
}
// 按自定义拼接格式返回
return this.getFullYear() + "-" + addZero(this.getMonth() + 1) + "-" + addZero(this.getDate()) + " " + addZero(this.getHours()) + ":" + addZero(this.getMinutes()) + ":" + addZero(this.getSeconds());
};
const s = 1490489230000 // 毫秒数
const date = new Date(s) // 转化成GMT标准时间
date.toLocaleString() // 调用重写后的方法 2017-03-26 08:47:10

9652

被折叠的 条评论
为什么被折叠?



