自定义格式
1 filters: { 2 formatDate: function(val, fmt) { 3 let value = parseInt(val); 4 if (!value) return "几天前"; 5 let getDate = new Date(value * 1000); 6 let o = { 7 "M+": getDate.getMonth() + 1, 8 "d+": getDate.getDate(), 9 "h+": getDate.getHours(), 10 "m+": getDate.getMinutes(), 11 "s+": getDate.getSeconds(), 12 "q+": Math.floor((getDate.getMonth() + 3) / 3), 13 S: getDate.getMilliseconds() 14 }; 15 if (/(y+)/.test(fmt)) { 16 fmt = fmt.replace( 17 RegExp.$1, 18 (getDate.getFullYear() + "").substr(4 - RegExp.$1.length) 19 ); 20 } 21 for (let k in o) { 22 if (new RegExp("(" + k + ")").test(fmt)) { 23 fmt = fmt.replace( 24 RegExp.$1, 25 RegExp.$1.length === 1 26 ? o[k] 27 : ("00" + o[k]).substr(("" + o[k]).length) 28 ); 29 } 30 } 31 return fmt; 32 } 33 }
评论相关时间过滤
1 /** 2 * 转换时间 3 * 24小时内的,显示为x小时前; 4 * 超过24小时的,显示为x天前; 5 * 超过一周的,显示月日; 6 * 今年以前的,显示年月日 7 * @param {时间戳} timespan 8 * @param {*} istime 9 */ 10 export function formatDate(timespan, istime = false) { 11 // 解决在ios设备上时间出现NAN的问题 12 timespan = String(timespan).replace(/-/g, "/"); 13 timespan = new Date(Date.parse(timespan)).getTime(); 14 15 // timespan = 1530518642787; 16 var dateTime = new Date(timespan); 17 var year = dateTime.getFullYear(); 18 var month = dateTime.getMonth() + 1; 19 var day = dateTime.getDate(); 20 var hour = dateTime.getHours(); 21 var minute = dateTime.getMinutes(); 22 var second = dateTime.getSeconds(); 23 var now = new Date(); 24 // var now_new = Date.parse(now.toDateString()); //typescript转换写法 25 var now_new = now.getTime(); 26 var milliseconds = 0; 27 var timeSpanStr; 28 milliseconds = now_new - timespan; 29 if (milliseconds <= 1000 * 60 * 1) { 30 timeSpanStr = '刚刚'; 31 } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { 32 timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'; 33 } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { 34 timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'; 35 } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 7) { 36 timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'; 37 } else if (milliseconds > 1000 * 60 * 60 * 24 * 7 && year == now.getFullYear()) { 38 timeSpanStr = month + '-' + day; 39 } else { 40 timeSpanStr = year + '-' + padZero(month) + '-' + padZero(day); 41 } 42 // else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) { 43 // timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute; 44 // } else { 45 // timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute; 46 // } 47 return timeSpanStr; 48 }