|
| 1 | +import { intervalToDuration, formatDuration } from "date-fns"; |
| 2 | +import { parsePhoneNumber, isValidPhoneNumber } from "libphonenumber-js"; |
| 3 | + |
| 4 | +export function formatPhoneNumber(value: string): string { |
| 5 | + if (!isValidPhoneNumber(value)) { |
| 6 | + return value; |
| 7 | + } |
| 8 | + const phoneNumber = parsePhoneNumber(value); |
| 9 | + if (phoneNumber) { |
| 10 | + return phoneNumber.formatInternational(); |
| 11 | + } |
| 12 | + return value; |
| 13 | +} |
| 14 | + |
| 15 | +export function phoneCountry(value: string): string { |
| 16 | + const phoneNumber = parsePhoneNumber(value); |
| 17 | + if (phoneNumber && phoneNumber.country) { |
| 18 | + const regionNames = new Intl.DisplayNames(undefined, { type: "region" }); |
| 19 | + return regionNames.of(phoneNumber.country) ?? "Earth"; |
| 20 | + } |
| 21 | + return "Earth"; |
| 22 | +} |
| 23 | + |
| 24 | +export function formatTimestamp(value: string): string { |
| 25 | + return new Date(value).toLocaleString(); |
| 26 | +} |
| 27 | + |
| 28 | +export function formatMoney(value: string | number): string { |
| 29 | + return new Intl.NumberFormat("en-US", { |
| 30 | + style: "currency", |
| 31 | + currency: "USD", |
| 32 | + }).format(typeof value === "string" ? parseInt(value) : value); |
| 33 | +} |
| 34 | + |
| 35 | +export function formatDecimal(value: string | number): string { |
| 36 | + return new Intl.NumberFormat("en-US", { |
| 37 | + style: "decimal", |
| 38 | + }).format(typeof value === "string" ? parseInt(value) : value); |
| 39 | +} |
| 40 | + |
| 41 | +export function formatBillingPeriod(value: string): string { |
| 42 | + return new Date(value).toLocaleDateString("en-US", { |
| 43 | + year: "numeric", |
| 44 | + month: "long", |
| 45 | + }); |
| 46 | +} |
| 47 | + |
| 48 | +export function humanizeTime(value: string): string { |
| 49 | + const durations = intervalToDuration({ |
| 50 | + start: new Date(), |
| 51 | + end: new Date(value), |
| 52 | + }); |
| 53 | + return formatDuration(durations); |
| 54 | +} |
0 commit comments