Intl.RelativeTimeFormatによる相対時間フォーマット
Intl.RelativeTimeFormatを使用して、「3日前」や「2時間後」のような相対時間文字列を任意のロケールでフォーマットします。numericモードとautoモード、スタイルオプション、サポートされる時間単位について学びます。
Intl.RelativeTimeFormat
詳細な説明
Intl.RelativeTimeFormat:人間が読める時間差
Intl.RelativeTimeFormatは「3日前」、「2時間後」、「昨日」のようなロケール依存の相対時間フレーズを生成します。
基本的な使用法
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'always' });
rtf.format(-1, 'day'); // "1 day ago"
rtf.format(-3, 'day'); // "3 days ago"
rtf.format(2, 'hour'); // "in 2 hours"
Numeric vs Autoモード
const always = new Intl.RelativeTimeFormat('en', { numeric: 'always' });
const auto = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
always.format(-1, 'day'); // "1 day ago"
auto.format(-1, 'day'); // "yesterday"
always.format(1, 'day'); // "in 1 day"
auto.format(1, 'day'); // "tomorrow"
autoモードは「昨日」「今日」「明日」「先週」「来年」などの特別な単語を利用可能な場合に使用します。
ロケール間の比較
new Intl.RelativeTimeFormat('ja', { numeric: 'auto' })
.format(-1, 'day'); // "昨日"
new Intl.RelativeTimeFormat('de', { numeric: 'auto' })
.format(-1, 'day'); // "gestern"
new Intl.RelativeTimeFormat('fr', { numeric: 'auto' })
.format(1, 'week'); // "la semaine prochaine"
サポートされる単位
year、quarter、month、week、day、hour、minute、second
重要な制限事項
Intl.RelativeTimeFormatは時間差を計算しません。数値は自分で計算する必要があります:
const diff = targetDate - Date.now();
const days = Math.round(diff / (1000 * 60 * 60 * 24));
rtf.format(days, 'day');
ユースケース
相対時間フォーマットは、ソーシャルメディアフィード(「3時間前に投稿」)、通知システム(「30分後にミーティング」)、チャットアプリケーション(「最終オンライン:昨日」)、バージョン管理インターフェース(「2日前にコミット」)で広く使われています。Intl.RelativeTimeFormatがなければ、開発者はサポートするすべての言語でこれらのフレーズの翻訳テーブルを維持する必要がありました。