Intl.DateTimeFormatによるロケール別日付・時刻フォーマット
Intl.DateTimeFormatを使用して、任意のロケールの日付と時刻をフォーマットします。dateStyle、timeStyle、コンポーネントオプション、およびロケール間での日付順序やカレンダーシステムの違いについて学びます。
Intl.DateTimeFormat
詳細な説明
Intl.DateTimeFormat:ロケール対応の日付と時刻
日付フォーマットは、ロケール間で最も多くのバリエーションがある領域の1つです。月/日の順序、区切り文字、カレンダーシステム、時刻慣例がすべて異なります。
日付順序は大きく異なる
const date = new Date('2025-03-15T14:30:00');
new Intl.DateTimeFormat('en-US').format(date); // "3/15/2025"
new Intl.DateTimeFormat('en-GB').format(date); // "15/03/2025"
new Intl.DateTimeFormat('ja-JP').format(date); // "2025/3/15"
new Intl.DateTimeFormat('de-DE').format(date); // "15.3.2025"
new Intl.DateTimeFormat('ko-KR').format(date); // "2025. 3. 15."
dateStyleとtimeStyleの使用
const opts = { dateStyle: 'full', timeStyle: 'long' };
new Intl.DateTimeFormat('en-US', opts).format(date);
// "Saturday, March 15, 2025 at 2:30:00 PM GMT+9"
new Intl.DateTimeFormat('ja-JP', opts).format(date);
// "2025年3月15日土曜日 14:30:00 JST"
利用可能なスタイル:full、long、medium、short。
12時間制 vs 24時間制
new Intl.DateTimeFormat('en-US', {
hour: 'numeric', minute: 'numeric', hour12: true,
}).format(date); // "2:30 PM"
new Intl.DateTimeFormat('de-DE', {
hour: 'numeric', minute: 'numeric', hour12: false,
}).format(date); // "14:30"
カレンダーシステム
一部のロケールはデフォルトで非グレゴリオ暦を使用します:
// 日本の元号
new Intl.DateTimeFormat('ja-JP-u-ca-japanese', {
dateStyle: 'full',
}).format(date); // "令和7年3月15日土曜日"
// イスラム暦(ヒジュラ暦)
new Intl.DateTimeFormat('ar-SA-u-ca-islamic', {
dateStyle: 'full',
}).format(date);
ユースケース
日付フォーマットはほぼすべてのアプリケーションの基本です。カレンダーアプリはローカルで期待される順序(米国はMDY、ヨーロッパはDMY、日本はYMD)で日付を表示する必要があります。スケジューリングツールはロケールに基づいて12時間制または24時間制で時刻を表示する必要があります。Intl.DateTimeFormatは外部の日付ライブラリなしでこれらすべてのケースを処理します。