毫秒数(如:1541561246000)转日期(2018-11-07 11:27:26)
先建一个timeUtil.ts的文件,将格式化方法作为公共文件可以全局调用
export function formatDate(fmt: string,time: Date) { // author: meizz
const a = new Date()
const o: any = {
'M+': time.getMonth() + 1, // 月份
'd+': time.getDate(), // 日
'h+': time.getHours(), // 小时
'm+': time.getMinutes(), // 分
's+': time.getSeconds(), // 秒
'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
'S': time.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ?
(o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
};
调用时,先引入上面文件内的formatDate方法
import { formatDate } from '@/utils/timeUtil'
方法一:在方法中使用
/** 转换时间格式的计算属性 */
get createTimeFormat() {
if (this.message.createTime === null) {
return ''
}
return formatDate('yyyy-MM-dd hh:mm:ss', new Date(this.message.createTime))
}
方法二:利用filters
先定义好filters方法
@Component({
name:'ScreenMessage',
components:{ LocationMessage },
filters: {
format: (value: number) => formatDate('yyyy-MM-dd hh:mm:ss',new Date(value))
}
})
在html中利用管道符 “ | ”
<p class="msg_time">{{ message.createTime | format }}</p>