使用vue.js怎么把時間戳日期格式化?


一、問題

在頁面中使用Vue通過 {{ data }}來取值,如果數據是日期取出來則是時間戳。

 

 二、解決方案

  單獨定義用於時間格式化的js 函數date.js,代碼如下。在頁面中引入date.js,通過{{formatDate(data)}}將時間戳轉換為指定日期格式。

 1 //給內置的Date對象新增方法Format
 2 Date.prototype.Format = function (fmt) {  3     var o = {  4         "M+": this.getMonth() + 1, //月份
 5         "d+": this.getDate(), //
 6         "h+": this.getHours(), //小時
 7         "m+": this.getMinutes(), //
 8         "s+": this.getSeconds(), //
 9         "q+": Math.floor((this.getMonth() + 3) / 3), //季度
10         "S": this.getMilliseconds() //毫秒
11  }; 12     if (/(y+)/.test(fmt)) 13         fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 14     for (var k in o) 15         if (new RegExp("(" + k + ")").test(fmt)) 16             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); 17     return fmt; 18 }; 19 
20 //工具方法
21 function formatDate(timestramp) { 22     return new Date(timestramp).Format('yyyy-MM-dd'); 23 }

 

使用date.js后效果如圖。

 


免責聲明!

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



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