I tend to format my styles. Although you can do that following different criteria, my main criteria is aesthetic.
I created microsoft-capitalize; it follows Microsoft Copywriting styleguide and it’s simple and intuitive:
const capitalize = require('microsoft-capitalize')
capitalize('Microlink CDN: Global Edge Cache')
// => 'Microlink CDN: Global edge cache'
Internationalization is difficult to get right at the best of times, luckily there is a well supported API for it now in most browsers.
The method toLocaleString() will format the current Number
/Date
/Object
state into an international string locale representation.
const formatDate = ((date = new Date()),
({ lang = 'en-us', month = 'short', day = 'numeric', year = 'numeric' } = {}) =>
new Date(date).toLocaleString(lang, { month, day, year }))
There is another way to format dates, using Intl.DateTimeFormat. It’s specially useful for converting a timestamp to a specific timezone:
const prettyDate = timestamp =>
`[${new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZone: 'Europe/Madrid', // this is my local timezone!
hour12: false
}).format(new Date(timestamp))}]`
The same approach could be used for format a Number
:
const formatNumber = ({ style = 'currency', currency = 'CAD' } = {}) => (
n,
lang = 'en-US'
) => n.toLocaleString('de-DE', { style, currency })
Using it on action
const formatter = formatNumber()
const amount = 1034532
formatter(1034532) // 🇺🇸 USA
formatter(1034532, 'de-DE') // 🇩🇪 Germany
formatter(1034532, 'ar-EG') // 🇺🇪🇬 Egypt
You can use the browser for getting the user language preference:
const locale = navigator.language || navigator.userLanguage || 'en-US'
That’s could be a good point to start. Next step could remember the user preference and store it associated with the user profile settings.
The Intl.RelativeTimeFormat makes easy to formate relative time.
const formatTime = (
date1 = new Date(),
date2 = new Date(),
{ lang = 'en-us', unit = 'seconds', ...opts } = {}
) => new Intl.RelativeTimeFormat(lang, opts).format(date2 - date1, unit)
const listFormat = (list, { lang = 'en-us', ...opts } = {}) => new Intl.ListFormat(lang, opts).format(list)
listFormat(['Paco']) // "Paco"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe'], { type: 'disjunction' }) // "Paco or Pepe"
Written by Kiko Beats
Kiko Beats
Web is the Platform. Programmer, Computer Science & Software Engineer.