第一个参数是Date类型的时间
第二个参数是想要格式化的类型,是一个字符串。其中y代表年,M代表月,d代表日,h代表时,m代表分,s代表秒。1970-01-01 12:00:00 就可以写为yyyy-MM-dd hh:mm:ss
export function formatDate(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
}
}
return fmt
}