/**
* 时间格式函数
*
* @export
* @param {any} [date=new Date()]
* @param {string} [format='YYYY-MM-DD']
* @returns
*
* 可传参数
* 2021/10/1 10:00:00 (string类型)
* 2021.10.1 10:00:00 (string类型)
* 2021-10-1 10:00:00 (string类型)
* 时间戳9位或13位(number类型)
* 不传参数默认当前时间
*/
export function DateFormat (date = new Date(), format = 'YYYY-MM-DD') {
let time = ''
if (!date) return ''
if (!(date instanceof Date)) {
const reg = new RegExp(/^[1-9]\d{9}$/g).test(date + '')
const reg1 = new RegExp(/^[1-9]\d{12}$/g).test(date + '')
const reg2 = new RegExp(/^[1-9]\d{3}[-/\.]\d{1,2}[-/\.]\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$/g).test(date)
if (reg) {
time = new Date(parseInt(date) * 1000)
} else if (reg1) {
time = new Date(parseInt(date))
} else if (reg2) {
time = new Date(date)
} else {
return ''
}
} else {
time = date
}
const year = time.getFullYear()
const month = time.getMonth() + 1
const day = time.getDate()
const hour = time.getHours()
const min = time.getMinutes()
const sec = time.getSeconds()
return format
.replace('YYYY', year)
.replace('MM', +month >= 10 ? month : `0${month}`)
.replace('DD', +day >= 10 ? day : `0${day}`)
.replace('HH', +hour >= 10 ? hour : `0${hour}`)
.replace('mm', +min >= 10 ? min : `0${min}`)
.replace('ss', +sec >= 10 ? sec : `0${sec}`)
}
DateFormat 时间格式匹配,自动补零
于 2022-04-27 18:27:41 首次发布