Is it possible to translate words "day", "week", "month", "year" with pure js in modern browsers (Intl API)?

Viewed 177

Task is to display subscription price like 5$ / month in different locales.

I can manage price part with Intl nicely, but stuck with time period translating part.
I can use my own translation strings, but would prefer to use default Intl version if possible.

2 Answers

Use Intl.DisplayNames with type datetimefield from the Intl API.

const trans = (translate, locale = 'en') => {
  return new Intl.DisplayNames(locale, { type: 'dateTimeField' }).of(translate);
}

for (lang of [ 'en', 'nl', 'fr', 'zh-Hant' ]) {
  console.log(`3$ / ${trans('month', lang)}`);
}
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

3$ / month
3$ / maand
3$ / mois
3$ / 月

This api is capable of translating almost every date/time strings.
Overview of supported/translatable values:

day hour minute second
year month quarter
weekOfYear weekday era dayPeriod

You can use the DisplayNames method and set type = 'dateTimeField'

example:

const dn = new Intl.DisplayNames('pt', {type: 'dateTimeField'});
console.log(dn.of('era')); // logs 'era'
console.log(dn.of('year')); // logs 'ano'
console.log(dn.of('month')); // logs 'mês'
console.log(dn.of('quarter')); // logs 'trimestre'
console.log(dn.of('weekOfYear')); // logs 'semana'
console.log(dn.of('weekday')); // logs 'dia da semana'
console.log(dn.of('dayPeriod')); // logs 'AM/PM'
console.log(dn.of('day')); // logs 'dia'
console.log(dn.of('hour')); // logs 'hora'
console.log(dn.of('minute')); // logs 'minuto'
console.log(dn.of('second')); // logs 'segundo'

source https://docs.w3cub.com/javascript/global_objects/intl/displaynames/displaynames

Related