公開日: 2025 年 3 月 20 日
ウェブページに表示される一般的な情報には、特定のイベントまでの残り時間や、イベント発生からの経過時間などがあります。これは通常、時間の長さを時間、分、秒、またはその他の便利な時間単位で伝える文字列として表されます。
Intl.DurationFormat
は、追加の JavaScript を必要とせずに、ブラウザで国際化のニーズを考慮しながら、この処理を行う便利な機能です。2025 年 3 月より、ベースラインの新規利用可能になりました。
Intl.DurationFormat
の仕組み
Intl.DurationFormat
は、インスタンス化すると、経過時間を示す文字列を返すクラスです。文字列を生成する時間単位に対応するキーと値を含むオブジェクトを指定します。
// Specify the duration:
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 yr, 20 hr, 15 min, 35 sec'
new Intl.DurationFormat('en').format(duration);
長い形式の文字列を返すには、コンストラクタの 2 番目の引数で style
オプションに 'long'
の値を渡します。
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 year, 20 hours, 15 minutes, 35 seconds'
new Intl.DurationFormat('en', { style: 'long' }).format(duration);
これまでの例では、英語の文字列が生成されています。これは国際化機能であるため、有効なロケールを渡して、必要なサポート対象言語でフォーマットされた文字列を取得できることが、この機能の真の利点です。
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 Jahr, 20 Stunden, 15 Minuten und 35 Sekunden'
new Intl.DurationFormat('de', { style: 'long' }).format(duration);
// Output: '1 año, 20 horas, 15 minutos y 35 segundos'
new Intl.DurationFormat('es', { style: 'long' }).format(duration);
// Output: '1年20小时15分钟35秒钟'
new Intl.DurationFormat('zh', { style: 'long' }).format(duration);
// Output: '1 år, 20 timer, 15 minutter og 35 sekunder'
new Intl.DurationFormat('no', { style: 'long' }).format(duration);
// Output: 'mwaka 1, saa 20, dakika 15 na sekunde 35'
new Intl.DurationFormat('sw', { style: 'long' }).format(duration);
これらの例は、この新機能でできることのほんの一部にすぎません。機能の詳細については、MDN の Intl.DurationFormat
のドキュメントをご覧ください。