time.ts 898 B

12345678910111213141516171819202122
  1. type TimeKey =
  2. | "common.time.justNow"
  3. | "common.time.minutesAgo.short"
  4. | "common.time.hoursAgo.short"
  5. | "common.time.daysAgo.short"
  6. type Translate = (key: TimeKey, params?: Record<string, string | number>) => string
  7. export function getRelativeTime(dateString: string, t: Translate): string {
  8. const date = new Date(dateString)
  9. const now = new Date()
  10. const diffMs = now.getTime() - date.getTime()
  11. const diffSeconds = Math.floor(diffMs / 1000)
  12. const diffMinutes = Math.floor(diffSeconds / 60)
  13. const diffHours = Math.floor(diffMinutes / 60)
  14. const diffDays = Math.floor(diffHours / 24)
  15. if (diffSeconds < 60) return t("common.time.justNow")
  16. if (diffMinutes < 60) return t("common.time.minutesAgo.short", { count: diffMinutes })
  17. if (diffHours < 24) return t("common.time.hoursAgo.short", { count: diffHours })
  18. return t("common.time.daysAgo.short", { count: diffDays })
  19. }