如何将时间格式化
1 export function formatDate(date, fmt) { 2 //获取年份 3 //y+ -->1个或者多个y 4 //y* -->0个或者多个y 5 //y? -->0个或者1个y 6 if(/(y+)/.test(fmt)){ 7 // RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个字匹配(以括号为标志)字符串,一共有RegExp.$99个匹配项 8 //replace() 替换 (date.getFullYear() + '') 将获取到的年份(数字)拼接成字符串 9 // substr() 截取 比如传过来的是‘yyyy’ substr(4-4) 即截取0个 截取前2位 10 fmt = fmt.replace(RegExp.$1,(date.getFullYear() + '').substr(4-RegExp.$1.length)); 11 } 12 let o = { 13 'M+': date.getMonth() + 1, 14 'd+': date.getDate(), 15 'h+': date.getHours(), 16 'm+': date.getMinutes(), 17 's+': date.getSeconds() 18 }; 19 for (let k in o){ 20 if(new RegExp(`(${k})`).test(fmt)){ 21 let str = o[k] + ''; 22 fmt = fmt.replace(RegExp.$1,(RegExp.$1.length === 1) ? str : padLeftZero(str)); 23 } 24 } 25 return fmt 26 }; 27 function padLeftZero(str) { 28 //会有4:4:4 padLeftZero(str) {} 将其转化成04:04:04 29 return ('00' + str).substr(str.length) //截取 30 }
在所需要的文件中使用
<!-- 过滤器 时间戳 -->
<span class="data">{{commentInfo.created | showDate }}</span>
1 import {formatDate} from "common/utils"; 2 export default { 3 name: "DetailCommentInfo", 4 props:{ 5 commentInfo:{ 6 type:Object, 7 default(){ 8 return {} 9 } 10 } 11 }, 12 filters:{ 13 showDate(value) { 14 //1.将时间戳转成Date对象 15 const date = new Date(value*1000); 16 // 2.将date进行格式化 17 return formatDate(date,'yyyy-MM-dd') 18 } 19 } 20 }
效果图:
Everyone cries! It's just that you learned to hide.