JavaScript Internationalization

January 21, 2018

Internationalization is difficult to get right at the best of times, luckily there is a well supported API for it now in most browsers.

Tip: Format dates with ease

(new Date()).toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'});
//=> August 17, 2016

— Sindre Sorhus πŸ‡³πŸ‡΄ (@sindresorhus) 4 de octubre de 2016

Using .toLocaleString() method

The method Object.prototype.toLocaleString() will format the current Number/Date/Object state into an international string locale representation.

First time I used it was on windtoday app, where I created a helper for easily format a timestamp based on a locale

const getFormatDate =  (timestamp, lang = 'en-us') =>
  new Date(timestamp).toLocaleString(lang, {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

In an international scenario a good approach could be get the language from the browser settings:

const locale = navigator.language || navigator.userLanguage; 

It’s useful for formatting money as well:

πŸ”₯ You can format currency with .toLocaleString() pic.twitter.com/Dagiw1QcNM

— Wes Bos πŸ”₯ (@wesbos) July 5, 2016

Bibliography