封装格式化时间方法
创建一个js文件formatDate.js,内容如下:
//方法一
export function formatDate(val) {var date = new Date(Number(val)); //时间戳为10位需*1000,时间戳为13位的话不需乘1000var Y = date.getFullYear() + "-";var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";var D = date.getDate() + " ";var h = date.getHours() + ":";var m = date.getMinutes() + ":";var s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());return Y + M + D + h + m + s;
}//方法二
export function formatDates(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);
}
使用
import {formatDate,formatDates} from '@/utils/formatDate'export default {data() {return {newsList: [],time: "1581672605401"}},created () {this.getNewsList()},filters: {//方法一fmtime(val) {return formatDate(val);},//使用封装中的方法二formatTime(val){let data=new Date(val)return formatDates(data,'yyyy-MM-dd hh:mm');}},methods: { },},}
<div v-for="d in newsList" :key="d.id"><div>{{time | fmtime}}</div><span>{{d.createdDate | formatTime}}</span></div>