Intl API — format ตัวเลข วันที่ และ relative time แบบ native
Intl API ให้ format ข้อมูลตาม locale ได้โดยไม่ต้องใช้ library — built-in ทุก modern browser
ตัวเลขและสกุลเงิน:
// ราคาสินค้า (THB)
new Intl.NumberFormat('th-TH', {
style: 'currency',
currency: 'THB',
}).format(45000);
// "฿45,000.00"
// ตัวเลขทั่วไป พร้อม separator
new Intl.NumberFormat('en-US').format(1234567);
// "1,234,567"
วันที่:
new Intl.DateTimeFormat('th-TH', {
dateStyle: 'long',
timeStyle: 'short',
}).format(new Date());
// "15 มิถุนายน 2569 12:30"
new Intl.DateTimeFormat('en-US', {
weekday: 'long', month: 'short', day: 'numeric',
}).format(new Date());
// "Sunday, Jun 15"
Relative time (เมื่อกี้ / 3 วันก่อน):
const rtf = new Intl.RelativeTimeFormat('th', { numeric: 'auto' });
rtf.format(-1, 'day'); // "เมื่อวาน"
rtf.format(-3, 'day'); // "3 วันที่ผ่านมา"
rtf.format(2, 'hour'); // "ใน 2 ชั่วโมง"
Plural rules — ภาษาอังกฤษ “1 item” vs “2 items”:
const pr = new Intl.PluralRules('en');
pr.select(1); // "one"
pr.select(2); // "other"