// 时间格式化
const formatTime = function formatTime(time, template) {
if (typeof time !== 'string') {
time = new Date().toLocaleString('zh-CN', { hour12: false })
}
if (typeof template !== 'string') {
template = '{0}年{1}月{2}日 {3}:{4}:{5}'
}
let arr = []
if (/^\d{8}$/.test(time)) {
let [, $1, $2, $3] = /^(\d{4})(\d{2})(\d{2})$/.exec(time)
arr.push($1, $2, $3)
} else {
arr = time.match(/\d+/g)
}
return template.replace(/\{(\d+)\}/g, (_, $1) => {
let item = arr[$1] || '00'
if (item.length < 2) item = '0' + item
return item
})
}
// 使用方法 formatTime('2023-09-06 01:02:03', '{0}-{1}-{2} {3}:{4}:{5}')
console.log(formatTime('20230906', '{0}-{1}-{2}')) // 2023-09-06
console.log(formatTime('2023-09-06', '{0}-{1}-{2} {3}:{4}:{5}')) // 2023-09-06 00:00:00
/* 如果只想获取几月节日,可以这么操作 */
console.log(formatTime('2023-09-06', '{1}-{2}')) // 09-06
// 剩下的自己可以多研究一下哈,就不一一例举了