数据库一般存的日期数据都是一个时间戳,很少存字符串
html code: {{ good.time | showDate}}
filters:{
showDate(value) {
//1.先将时间戳转化为日期格式
const date = new Date (value*1000) ;
//因为 new Date 中要传一个到毫秒的时间戳,而我们的时间戳是到秒,所以 * 1000
//2.将 date 进行格式化
return formatDate(date, "yyyy-MM-dd hh:mm:ss")
}
}
时间格式化的函数由于太常用了,因此要写到 utils.js 里方便调用.这么写的原因是因为 JS 原生还没有直接可以格式化的代码,等以后有了,就不用自己封装了。
export function formatDate (date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
}
}
return fmt
}
function padLeftZero (str) {
return ('00' + str).substr(str.length)