W JS wbudowany jest obiekt Intl, który dostarcza kilka przydatnych funkcji językowych. Najbardziej przydatne z nich to:
- Intl.DateTimeFormat() - pozwalający na stworzenie daty jako stringa w dowolnym języku.
- Intl.ListFormat() - pozwala na tworzenie list przedzielonych przecinkami i ustawienie jak ma być oddzielony ostatni item dla opcji 'i' oraz 'lub'. Jakiś rok temu pisałem podobny kod samodzielnie.
- Intl.NumberFormat() - do formatowania kwot w walucie. Częsty case przy prezentacji danych lub tworzeniu masek do inputów.
- Intl.RelativeTimeFormat() - przydaje się, jeśli w aplikacji wyświetlasz wartości typu "1 dzień temu", "za dwie godziny". Ta metoda pozwala na tworzenie stringów tego typu bez bibliotek.
Zapraszam do bliższego samodzielnego zapoznania się z tym przydatnym api.
Poniżej przykłady kodu z MDN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 | |
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738)); | |
console.log(new Intl.DateTimeFormat('pl-PL', {dateStyle: 'full'}).format(date)); | |
// niedziela, 20 grudnia 2020 | |
// 2 | |
const vehicles = ['Motor', 'bus', 'samochód']; | |
const formatter = new Intl.ListFormat('pl', { style: 'long', type: 'conjunction' }); | |
console.log(formatter.format(vehicles)); | |
// Motor, bus i samochód | |
const formatter2 = new Intl.ListFormat('pl', { style: 'short', type: 'disjunction' }); | |
console.log(formatter2.format(vehicles)); | |
// Motor, bus lub samochód | |
// 3 | |
const number = 123456.789; | |
console.log(new Intl.NumberFormat('pl-PL', { style: 'currency', currency: 'PLN' }).format(number)); | |
// expected output: "123.456,79 zł | |
// 4 | |
// Create a relative time formatter in your locale | |
// with default values explicitly passed in. | |
const rtf = new Intl.RelativeTimeFormat("pl", { | |
localeMatcher: "best fit", // other values: "lookup" | |
numeric: "always", // other values: "auto" | |
style: "long", // other values: "short" or "narrow" | |
}); | |
// Format relative time using negative value (-1). | |
console.log(rtf.format(-1, "day")); | |
// 1 dzień temu | |
// Format relative time using positive value (1). | |
console.log(rtf.format(1, "day")); | |
// za jeden dzień |
Brak komentarzy:
Prześlij komentarz