const dateFormat = (time, format) => {
if (!time) {
console.error('格式化时,时间不能为空')
return ''
}
const _time = typeof time === 'number' ? new Date(time) : time
let res = format;
const obj = {
'y+': _time.getFullYear(),
'M+': _time.getMonth() + 1,
'd+': _time.getDate(),
'h+': _time.getHours(),
'm+': _time.getMinutes(),
's+': _time.getSeconds()
}
for (let k in obj) {
if (new RegExp(`(${k})`).test(format)) {
res = res.replace(RegExp.$1, obj[k])
}
}
return res
}
console.log(dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'))
const getLastMonth = function() {
const t = new Date()
const currentMonth = t.getMonth()
t.setMonth(currentMonth - 1, 1)
return dateFormat(t, 'yyyy-MM')
}
console.log(getLastMonth())
const getLastWeekRange = function(type="yyyy-MM-dd") {
const currentTime = new Date()
const currentDay = currentTime.getDay()
const _milli = 24 * 60 * 60 * 1000
const end = currentTime.getTime() - (currentDay || 7) * _milli
const start = end - 6 * _milli
return [dateFormat(new Date(start), type), dateFormat(new Date(end), type)]
}
console.log(getLastWeekRange())