|
| 1 | +/** |
| 2 | + * Format a timestamp as a short relative string (e.g. "3m", "2h", "5d"). |
| 3 | + * Accepts either a Unix ms timestamp or an ISO date string. |
| 4 | + */ |
| 5 | +export function formatRelativeTimeShort(timestamp: number | string): string { |
| 6 | + const ms = |
| 7 | + typeof timestamp === "string" ? new Date(timestamp).getTime() : timestamp; |
| 8 | + const diff = Date.now() - ms; |
| 9 | + |
| 10 | + const minutes = Math.floor(diff / 60_000); |
| 11 | + const hours = Math.floor(diff / 3_600_000); |
| 12 | + const days = Math.floor(diff / 86_400_000); |
| 13 | + const weeks = Math.floor(days / 7); |
| 14 | + const months = Math.floor(days / 30); |
| 15 | + const years = Math.floor(days / 365); |
| 16 | + |
| 17 | + if (years > 0) return `${years}y`; |
| 18 | + if (months > 0) return `${months}mo`; |
| 19 | + if (weeks > 0) return `${weeks}w`; |
| 20 | + if (days > 0) return `${days}d`; |
| 21 | + if (hours > 0) return `${hours}h`; |
| 22 | + if (minutes > 0) return `${minutes}m`; |
| 23 | + return "now"; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Format a timestamp as a longer relative string (e.g. "3 minutes ago", "1 day ago"). |
| 28 | + * Falls back to a locale date for anything older than a week. |
| 29 | + * Accepts either a Unix ms timestamp or an ISO date string. |
| 30 | + */ |
| 31 | +export function formatRelativeTimeLong(timestamp: number | string): string { |
| 32 | + const date = |
| 33 | + typeof timestamp === "string" ? new Date(timestamp) : new Date(timestamp); |
| 34 | + const diff = Date.now() - date.getTime(); |
| 35 | + |
| 36 | + const seconds = Math.floor(diff / 1000); |
| 37 | + const minutes = Math.floor(seconds / 60); |
| 38 | + const hours = Math.floor(minutes / 60); |
| 39 | + const days = Math.floor(hours / 24); |
| 40 | + |
| 41 | + if (seconds < 60) return "just now"; |
| 42 | + if (minutes < 60) |
| 43 | + return minutes === 1 ? "1 minute ago" : `${minutes} minutes ago`; |
| 44 | + if (hours < 24) return hours === 1 ? "1 hour ago" : `${hours} hours ago`; |
| 45 | + if (days < 7) return days === 1 ? "1 day ago" : `${days} days ago`; |
| 46 | + |
| 47 | + return date.toLocaleDateString(undefined, { |
| 48 | + month: "short", |
| 49 | + day: "numeric", |
| 50 | + year: "numeric", |
| 51 | + }); |
| 52 | +} |
0 commit comments