utils.ts
69 lines
| 1 | import {formatDistanceToNow} from 'date-fns'; |
| 2 | |
| 3 | /** |
| 4 | * @since 4.0.0 |
| 5 | */ |
| 6 | export function amountFormatter( |
| 7 | currency: Intl.NumberFormatOptions['currency'], |
| 8 | options?: Intl.NumberFormatOptions |
| 9 | ): Intl.NumberFormat { |
| 10 | return new Intl.NumberFormat(navigator.language, { |
| 11 | style: 'currency', |
| 12 | currency: currency, |
| 13 | ...options, |
| 14 | }); |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * @since unreleased |
| 19 | */ |
| 20 | export function formatTimestamp(timestamp: string | null | undefined, useComma: boolean = false): string { |
| 21 | // Handle null, undefined, or empty string |
| 22 | if (!timestamp) { |
| 23 | return '—'; |
| 24 | } |
| 25 | |
| 26 | const date = new Date(timestamp); |
| 27 | |
| 28 | // Check if the date is valid |
| 29 | if (isNaN(date.getTime())) { |
| 30 | return '—'; |
| 31 | } |
| 32 | |
| 33 | const day = date.getDate(); |
| 34 | const ordinal = (day: number): string => { |
| 35 | if (day > 3 && day < 21) return 'th'; |
| 36 | switch (day % 10) { |
| 37 | case 1: |
| 38 | return 'st'; |
| 39 | case 2: |
| 40 | return 'nd'; |
| 41 | case 3: |
| 42 | return 'rd'; |
| 43 | default: |
| 44 | return 'th'; |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | const dayWithOrdinal = `${day}${ordinal(day)}`; |
| 49 | const month = date.toLocaleString('en-US', {month: 'long'}); |
| 50 | const year = date.getFullYear(); |
| 51 | const time = date.toLocaleString('en-US', {hour: 'numeric', minute: '2-digit', hour12: true}).toLowerCase(); |
| 52 | const separator = useComma ? ', ' : ' • '; |
| 53 | |
| 54 | return `${dayWithOrdinal} ${month} ${year}${separator}${time}`; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Returns a relative time string for a given date (e.g. "Today" or "2 days ago") |
| 59 | * |
| 60 | * @since unreleased |
| 61 | */ |
| 62 | export function getRelativeTimeString(date: Date): string { |
| 63 | const now = new Date(); |
| 64 | if (date.toDateString() === now.toDateString()) { |
| 65 | return 'Today'; |
| 66 | } |
| 67 | return formatDistanceToNow(date, {addSuffix: true}); |
| 68 | } |
| 69 |