1 const REGEX = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2})/ 2 /** 3 * @function format time 4 * @param val, format 5 * @return {string} 6 * @example 7 * <template> 8 * <div> 9 * <span>{{item.time | formatTime('yyyy/MM/dd hh:mm:ss')}}</span> 10 * </div> 11 * </template> 12 * import {formatTime} from '../../library/timeFormat' 13 * export default { 14 * filters: {formatTime} 15 * } 16 */ 17 export const formatTime = (val, format) => { 18 if (val) { 19 /** 20 * @instructions 如果不是时间戳格式,且含有字符 '-' 则将 '-' 替换成 '/' && 删除小数点及后面的数字 21 * @reason 将 '-' 替换成 '/' && 删除小数点及后面的数字 的原因是safari浏览器仅支持 '/' 隔开的时间格式 22 */ 23 if (val.toString().indexOf('-') > 0) { 24 val = val.replace(/T/g, ' ').replace(/.[d]{3}Z/, '').replace(/(-)/g, '/') // 将 '-' 替换成 '/' 25 val = val.slice(0, val.indexOf('.')) // 删除小数点及后面的数字 26 } 27 let date = new Date(val) 28 date.setHours(date.getHours() + 8) 29 const [whole, yy, MM, dd, hh, mm, ss] = date.toISOString().match(REGEX) 30 const year = new Date().getFullYear() 31 const month = new Date().getMonth() + 1 32 const dates = new Date().getDate() 33 if (format) { 34 return format 35 .replace('yyyy', yy) 36 .replace('yy', yy.slice(2)) 37 .replace('MM', MM) 38 .replace('dd', dd) 39 .replace('hh', hh) 40 .replace('mm', mm) 41 .replace('ss', ss) 42 } else { 43 return [yy, MM, dd].join('-') + ' ' + [hh, mm, ss].join(':') 44 } 45 } else { 46 return '--' 47 } 48 }