2

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.

0stone0
  • 34,288
  • 4
  • 39
  • 64

2 Answers2

4

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
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Working nice in Chrome and Firefox, but exploded in Safari 14.1.2 with ```RangeError: type must be either "language", "region", "script", or "currency"``` – Tamal Govinda das Jan 01 '22 at 16:28
2

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