const dateFormat = (date, format = 'YYYY-MM-DD hh:mm:ss') => {
try {
if (!date) return
date = new Date(date)
// 判定输入值是否可转换为日期
if (isNaN(date.getTime())) {
console.log(date)
return null
}
const detail = parse(date)
let result = format
Object.keys(detail).forEach(key => {
const val = detail[key]
result = result.replace(key, val)
})
console.log(result)
return result
} catch (err) {
console.log('Found Error:')
console.log(err)
}
}
// 解析
const parse = (date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hours = date.getHours()
const minutes = date.getMinutes()
const seconds = date.getSeconds()
// 其中如 M 和 MM 的关系,为后者为前者的对应补全值
// * 对应的,必须将 MM 放在前边,避免在遍历属性时,先便利到了 M 而导致提前修改值,从而出现替换错误
return {
YYYY: year,
MM: add0(month),
M: month,
DD: add0(day),
D: day,
hh: add0(hours),
h: hours,
mm: add0(minutes),
m: minutes,
ss: add0(seconds),
s: seconds,
}
}
// 值补全
const add0 = (n) => {
return n > 9 ? n : '0' + n
}
// 测试
dateFormat(Date.now(), 'YYYY/M/DD hh:mm')
02-10
708
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)