Web Intl Formatters
Frequently creating Intl.NumberFormat or Intl.DateTimeFormat instances incurs unnecessary performance overhead. ts-intl encapsulates standard Web Intl APIs and provides a built-in instance caching mechanism.
Obtaining Formatter Instances
Method 1: Obtain getFormatter via createI18n (Recommended)
This approach directly inherits preset format rules, timezone, and error handling configurations from the global settings:
import { createI18n } from "@aaakul/ts-intl";
export const { getTranslations, getFormatter } = createI18n({
defaultLanguage: "en-US",
formats: {
number: {
usd: { style: "currency", currency: "USD" },
compact: { notation: "compact" },
},
dateTime: {
short: { dateStyle: "short" },
},
},
messages: {
"en-US": {},
},
});
const formatter = getFormatter("en-US");
Method 2: Call createFormatter(options) Independently
Suitable for standalone components or utility modules that do not depend on a full i18n instance:
import { createFormatter } from "@aaakul/ts-intl";
const formatter = createFormatter({
locale: "en-US",
formats: {
number: { usd: { style: "currency", currency: "USD" } },
},
});
Core Formatting Features
Number & Currency Formatting
formatter.number(1234567.89);
// "1,234,567.89"
formatter.number(2500, "usd");
// "$2,500.00"
formatter.number(1500000, "compact");
// "1.5M"
Date & Time
formatter.dateTime(new Date(), { dateStyle: "long" });
// "September 18, 2026"
formatter.dateTimeRange(new Date("2026-09-01"), new Date("2026-09-05"));
// "9/1/2026 – 9/5/2026"
Relative Time Calculation
Automatically matches time units based on the time difference:
const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
formatter.relativeTime(twoHoursAgo);
// "2 hours ago"
Lists & Localized Display Names
formatter.list(["TypeScript", "Astro", "UnoCSS"]);
// "TypeScript, Astro, and UnoCSS"
formatter.displayName("ja-JP", { type: "language" });
// "Japanese (Japan)"
formatter.displayName("ja", { type: "language" });
// "Japanese"