2024-09-30 18:53:57 +08:00
|
|
|
export function relativeTime(timestamp: string | number) {
|
2024-09-29 20:57:24 +08:00
|
|
|
const date = new Date(timestamp)
|
|
|
|
const now = new Date()
|
|
|
|
const diffInSeconds = (now.getTime() - date.getTime()) / 1000
|
|
|
|
const diffInMinutes = diffInSeconds / 60
|
|
|
|
const diffInHours = diffInMinutes / 60
|
|
|
|
|
2024-09-30 18:53:57 +08:00
|
|
|
if (Number.isNaN(date.getDay())) {
|
|
|
|
return undefined
|
|
|
|
} else if (diffInSeconds < 60) {
|
|
|
|
return "刚刚"
|
2024-09-29 20:57:24 +08:00
|
|
|
} else if (diffInMinutes < 60) {
|
|
|
|
const minutes = Math.floor(diffInMinutes)
|
2024-09-30 18:53:57 +08:00
|
|
|
return `${minutes}分钟前`
|
2024-09-29 20:57:24 +08:00
|
|
|
} else if (diffInHours < 24) {
|
|
|
|
const hours = Math.floor(diffInHours)
|
2024-09-30 18:53:57 +08:00
|
|
|
return `${hours}小时前`
|
2024-09-29 20:57:24 +08:00
|
|
|
} else {
|
|
|
|
const month = date.getMonth() + 1
|
|
|
|
const day = date.getDate()
|
|
|
|
return `${month}月${day}日`
|
|
|
|
}
|
|
|
|
}
|