| 1 | export function formatDistanceToNow(date: Date): string { |
| 2 | const seconds = Math.floor((new Date().getTime() - date.getTime()) / 1000) |
| 3 | |
| 4 | let interval = seconds / 31536000 |
| 5 | if (interval > 1) return Math.floor(interval) + ' years ago' |
| 6 | |
| 7 | interval = seconds / 2592000 |
| 8 | if (interval > 1) return Math.floor(interval) + ' months ago' |
| 9 | |
| 10 | interval = seconds / 86400 |
| 11 | if (interval > 1) return Math.floor(interval) + ' days ago' |
| 12 | |
| 13 | interval = seconds / 3600 |
| 14 | if (interval > 1) return Math.floor(interval) + ' hours ago' |
| 15 | |
| 16 | interval = seconds / 60 |
| 17 | if (interval > 1) return Math.floor(interval) + ' minutes ago' |
| 18 | |
| 19 | return Math.floor(seconds) + ' seconds ago' |
| 20 | } |
| 21 | |
| 22 | export function formatFileSize(bytes: number): string { |
| 23 | if (!Number.isFinite(bytes) || bytes < 0) return '0 B' |
| 24 | if (bytes === 0) return '0 B' |
| 25 | const k = 1024 |
| 26 | const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] |
| 27 | const i = Math.floor(Math.log(bytes) / Math.log(k)) |
| 28 | // Prevent index out of bounds for extremely large numbers |
| 29 | const unit = sizes[i] || sizes[sizes.length - 1] |
| 30 | const val = bytes / Math.pow(k, i) |
| 31 | |
| 32 | return parseFloat(val.toFixed(2)) + ' ' + unit |
| 33 | } |