function getTimeStatus(date) {
const now = new Date()
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const inputDate = new Date(date)
const inputYear = inputDate.getFullYear()
const inputMonth = inputDate.getMonth()
const inputDay = inputDate.getDate()
const dayDiff = Math.floor((today - inputDate) / 86400000)
// 计算相对于当前周的偏移量
const dayOfWeek = inputDate.getDay()
const currentDayOfWeek = now.getDay()
const weekDiff = dayDiff + (dayOfWeek < currentDayOfWeek ? 7 : 0)
if (weekDiff < 0) {
if (dayDiff === -1) return '前天'
if (dayDiff === -2) return '大前天'
return '上周'
} else if (weekDiff > 0) {
if (dayDiff === 1) return '明天'
if (dayDiff === 2) return '后天'
return '下周'
} else { // weekDiff === 0
if (dayDiff === 0) {
const hoursDiff = now.getHours() - inputDate.getHours()
if (hoursDiff < 24) {
if (hoursDiff < 12) return '今天'
return '当前周'
}
}
if (dayDiff === -1) return '昨天'
if (dayDiff === 1) return '明天'
return '当前周'
}
}
// 使用示例
console.log(getTimeStatus(new Date()))
console.log(getTimeStatus(new Date(Date.now() - 86400000)))
console.log(getTimeStatus(new Date(Date.now() + 86400000)))