用js將從后台得到的時間戳(毫秒數)轉換為想要的日期格式
得到后台從數據庫中拿到的數據我們希望格式是
2016年10月25日 17時37分30秒 或者 2016/10/25 17:37:30
然而我們前台得到的卻是一段數字(時間戳,毫秒數)
1477386005
我們要將時間戳轉化為我們想要的格式。
核心方法 :
1477386005是我從后台得到時間戳 (注意:有的時候得到的時間戳是已經乘以1000的)
var unixTimestamp = new Date( 1477386005*1000 ) ; commonTime = unixTimestamp.toLocaleString();
alert(commonTime);
這時候的結果是:
但是我希望轉換為我自己想要的格式,就在本頁面重寫一下 toLocaleString()方法即可。
Date.prototype.toLocaleString = function() { return this.getFullYear() + "年" + (this.getMonth() + 1) + "月" + this.getDate() + "日 " + this.getHours() + "點" + this.getMinutes() + "分" + this.getSeconds() + "秒"; };
結果為:
或者其他想要的格式:
Date.prototype.toLocaleString = function() { return this.getFullYear() + "/" + (this.getMonth() + 1) + "/" + this.getDate() + "/ " + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds(); };
結果為: