标题vue中 自定义时间格式化
1.首先创建时间格式化工具类 这里我命名为date.js
export default {
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 : this.padLeftZero(str))
}
}
return fmt
},
padLeftZero (str) {
return ('00' + str).substr(str.length)
}
};
2.在页面引用该js
import formatDate from '../../assets/js/date.js';//这里是引用js的路径
3.使用(注意第一个参数是date类型,第二个是你想要的样式:例如 Wed Jul 15 2020 10:35:29 GMT+0800 (中国标准时间),转换之后 2020-07-15,如果第二个参数为 “yyyy-MM-DD hh:mm:ss” 则输出的是 2020-07-15 10:39:01 )
formatDate.formatDate(new Date, "yyyy-MM-DD")
formatDate.formatDate(new Date, "yyyy-MM-DD hh:mm:ss")