js Intl API (Internationalization)

در جاوااسکریپت، Intl API (Internationalization API) ابزاری است برای فرمت کردن تاریخ، اعداد و متن‌ها بر اساس زبان و منطقه (Locale).
با استفاده از این API می‌توان برنامه‌های چندزبانه و سازگار با فرهنگ‌های مختلف ساخت.

🔹 فرمت کردن اعداد

const number = 1234567.89;

// فرمت فارسی (ایران)
const faFormatter = new Intl.NumberFormat("fa-IR").format(number);
console.log(faFormatter);

// فرمت انگلیسی (ایالات متحده)
const enFormatter = new Intl.NumberFormat("en-US").format(number);
console.log(enFormatter);

📌 خروجی:

۱٬۲۳۴٬۵۶۷٫۸۹
1,234,567.89

🔹 فرمت کردن ارزها (Currency)

const price = 2500.5;

const usdFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
}).format(price);

const irRialFormatter = new Intl.NumberFormat("fa-IR", {
  style: "currency",
  currency: "IRR"
}).format(price);

console.log(usdFormatter);
console.log(irRialFormatter);

📌 خروجی:

$2,500.50
۲٬۵۰۰ ﷼

🔹 فرمت کردن تاریخ

const date = new Date("2025-10-08T10:30:00");

const faDate = new Intl.DateTimeFormat("fa-IR").format(date);
const enDate = new Intl.DateTimeFormat("en-US").format(date);

console.log(faDate);
console.log(enDate);

📌 خروجی:

۸/۷/۱۴۰۴
10/8/2025

🔹 گزینه‌های پیشرفته برای تاریخ

const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};

const faFullDate = new Intl.DateTimeFormat("fa-IR", options).format(date);
console.log(faFullDate);

📌 خروجی نمونه:

سه‌شنبه، ۸ مهر ۱۴۰۴

🔹 کاربردهای دیگر Intl

  • Intl.Collator → مرتب‌سازی رشته‌ها بر اساس زبان

  • Intl.PluralRules → قوانین جمع برای زبان‌های مختلف

  • Intl.RelativeTimeFormat → نمایش زمان نسبی (مثلاً «2 روز پیش»)

  • Intl.ListFormat → فرمت لیست‌ها بر اساس زبان

نکته:

  • Intl API باعث می‌شود برنامه‌ها چندزبانه و سازگار با فرهنگ‌های مختلف باشند.

  • از ES6 به بعد در اکثر مرورگرهای مدرن پشتیبانی می‌شود.

  • همیشه بهتر است هنگام نمایش تاریخ، عدد یا متن به کاربران، Locale مناسب را مشخص کنید.