'get plural value for time units (days, hours, minutes) using Intl API
I'm trying to localize time units and I'm able to do so for singular (hour, day, minute) but I'm unable to find any way to figure out the plural equivalent (hours, days, minutes). Is it not supported or am I missing something obvious. I looked at Intl.PluralRules thinking that'd be helpful but with no luck. Would appreciate any tips.
let locale = "en-US";
let days = new Intl.DisplayNames(locale, { type: 'dateTimeField', style: 'long' }).of('day');
let hours = new Intl.DisplayNames(locale, { type: 'dateTimeField', style: 'long' }).of('hour');
console.log(days,hours);
Solution 1:[1]
You should take a look at Intl.RelativeTimeFormat.prototype.formatToParts(). This method returns three parts of a RelativeTimeFormat, last one of which is an object with time unit.
const rtf1 = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const parts = rtf1.formatToParts(10, 'seconds');
console.log(parts[2].value);
// expected output: " seconds"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Konstantin |