JS将YYYYMMDDHHMMSS格式化为YYYY-MM-DD HH:MM:SS
问题
将字符串YYYYMMddHHmmss
格式化成YYYY-MM-DD hh:mm:ss
解决方案
dateStr(dateStr) {
var pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;
//将时间格式化成 yyyy-MM-dd HH:mm:ss
var formatDateStr = dateStr.replace(pattern, '$1-$2-$3 $4:$5:$6');
return formatDateStr;
}
注意
用在vue中可能报以下错误
<template slot-scope="scope">
{{dateStr(scope.row.createTime)}}
</template>
TypeError: Cannot read properties of undefined (reading 'replace')
原因:数据来源可能为空
解决方案
在数据的标签里面添加判断 v-if
<template slot-scope="scope">
<span v-if="scope.row.createTime">
{{dateStr(scope.row.createTime)}}
</span>
</template>