用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();
    };

    結果為:

     

 
        

文章參考:檸檬旋風腿

友情鏈接:時間戳轉化網站  W3School


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM