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