Why doesn’t NodeJS localize my date names?
Be aware: Default NodeJS builds provide full date localization only for English
Lately, we ran into an issue where date localization would work in the browser but not in NodeJS.
The following snippet returns the pretty name of the month:
const march = new Date('2018–03–01');
const en = new Intl.DateTimeFormat('en', { month: ‘long’ });
en.format(march);
// Returns: "March"
In the browser, changing the locale to de
returns the correct pretty name:
const march = new Date('2018–03–01');
const de = new Intl.DateTimeFormat('de', { month: ‘long’ });
de.format(march);
// Returns: "März"
Yet, running the same code in NodeJS returns “M10” (instead of “März”).
Why does the browser localize the month name but NodeJS doesn’t?
It turns out that default NodeJS builds contain only a limited set of localization data (full details). In a nutshell, only English will be supported. If you want localization for all locales, you need to recompile NodeJS with the--with-intl=full-icu
flag.
We ended up going a different route to avoid forcing developers to use a non-standard version of NodeJS: Instead of using the build-in localization via Intl.DateTimeFormat
, we use now momentjs:
const march = new Date('2018–03–01');
moment(march).locale('de').format('MMMM');
// Returns: "März"
Happy coding!
Photo: Mike Cohen