毫秒转换日期

时间:2024-02-19 14:47:12

//原方法转换自带格式:xxxx-‎xx月-xx‎  ‎ ‎xx‎:‎xx‎:‎xx

一,重写方法前:

例:time:1534301216395

调用:changeTime(time):

function changeTime(time){
    var commonTime = "";
    if(time){
        var unixTimestamp = new Date(time*1) ;
        commonTime = unixTimestamp.toLocaleString();
    }
     return commonTime;
}

结果:

‎2018-8-15 10:46:56
//转换为自己想要的格式,重写 toLocaleString()。

二,重写方法后:

例:time:1534301216395

调用:changeTime(time):

Date.prototype.toLocaleString = function() {
    return this.getFullYear() + "年" + (this.getMonth() + 1) + "月" + this.getDate() + "日 " + this.getHours() + "点" + this.getMinutes() + "分" + this.getSeconds() + "秒";
};

结果:

2018年8月15日 10点46分56秒
三,第三种方法:

例:time:1534301216395

function changeTime(time){
if(time){
var oDate = new Date(time*1),
oYear = oDate.getFullYear(),
oMonth = oDate.getMonth()+1,
oDay = oDate.getDate(),
oHour = oDate.getHours(),
oMin = oDate.getMinutes(),
oSen = oDate.getSeconds(),
oTime = oYear +\'-\'+ getBz(oMonth) +\'-\'+ getBz(oDay) +\' \'+ getBz(oHour) +\':\'+ getBz(oMin) +\':\'+getBz(oSen);//拼接时间
return oTime;
}else{
return "";
}

}
//补0
function getBz(num){
if(parseInt(num) < 10){
num = \'0\'+num;
}
return num;
}
结果:

2018-08-15 10:46:56

原文:https://blog.csdn.net/sevenmt/article/details/81700759