众所周知,时间格式化在开发中出现的频率非常高,原因是服务器返回的是一段时间戳。
Vue项目中添加全局过滤器,遇到就用CV大法。
Vue.filter('dateFormat', function (time) {
const dt = new Date(time) //new实例
const y = dt.getFullYear() //获取年
//获取月 日 时等等 其中月默认从0开始所以+1
//使用空字符串转为string类型
//使用padStart方法补0
const m = (dt.getMonth() + 1 + '').padStart(2, '0')
const d = (dt.getDate() + '').padStart(2, '0')
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
})
过滤器调用
{{时间戳 | dateFormat}}