使用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