newsnow/shared/utils.ts

29 lines
840 B
TypeScript
Raw Normal View History

2024-09-30 18:53:57 +08:00
export function relativeTime(timestamp: string | number) {
2024-10-06 00:31:43 +08:00
if (!timestamp) return undefined
2024-09-29 20:57:24 +08:00
const date = new Date(timestamp)
2024-10-06 00:31:43 +08:00
if (Number.isNaN(date.getDay())) return undefined
2024-09-29 20:57:24 +08:00
const now = new Date()
const diffInSeconds = (now.getTime() - date.getTime()) / 1000
const diffInMinutes = diffInSeconds / 60
const diffInHours = diffInMinutes / 60
2024-10-06 00:31:43 +08:00
if (diffInSeconds < 60) {
2024-09-30 18:53:57 +08:00
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}`
}
}
2024-10-08 20:49:19 +08:00
export function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}