export const getDate = date => {
if (date instanceof Date) {
return date
}
if (typeof date === 'number') {
return new Date(date)
}
if (typeof date === 'string') {
if (date) {
// eslint-disable-next-line no-useless-escape
date = date.replace(/\-/g, '/')
let newDate = new Date(date)
// 这里判断Invalid Date的清空,做浏览器兼容性处理
if (isNaN(newDate.getTime())) {
date = date.replace(/\//g, '-')
newDate = new Date(date)
}
return newDate
}
return new Date()
}
return new Date()
}
/**
* 自动加'0'
* @param time
*/
export const padDate = time => (time < 10 ? '0' + time : time + '')
/**
* 转换时间
* @param time 时间
* @param format 格式
* @param fillZero 是否自动补零
*/
export const formatDateNew = (time, format = 'YYYY-MM-DD HH:mm', fillZero = true) => {
const date = getDate(time)
const week = ['日', '一', '二', '三', '四', '五', '六']
return format.replace(/YYYY|yyyy|YY|yy|MM|DD|HH|hh|mm|SS|ss|week/g, key => {
switch (key) {
case 'YYYY':
case 'yyyy':
return date.getFullYear()
case 'YY':
case 'yy':
return (date.getFullYear() + '').slice(2)
case 'MM':
return fillZero ? padDate(date.getMonth() + 1) : date.getMonth() + 1
case 'DD':
return fillZero ? padDate(date.getDate()) : date.getDate()
case 'HH':
case 'hh':
return fillZero ? padDate(date.getHours()) : date.getHours()
case 'mm':
return fillZero ? padDate(date.getMinutes()) : date.getMinutes()
case 'SS':
case 'ss':
return fillZero ? padDate(date.getSeconds()) : date.getSeconds()
case 'week':
return week[date.getDay()]
}
})
}