JavaScriptで日付のフォーマットを行う際、`Intl.DateTimeFormat()`は非常に便利なメソッドです。このメソッドを使用することで、様々な形式で日付を表示することができます。
Intl.DateTimeFormat()の基本的な使い方
const date = new Date();
const formatter = new Intl.DateTimeFormat('ja-JP');
console.log(formatter.format(date));
// 出力例: 2024/2/20オプションを使用したカスタマイズ
より詳細な日付フォーマットを指定したい場合は、オプションを使用します。
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
const formatter = new Intl.DateTimeFormat('ja-JP', options);
console.log(formatter.format(date));
// 出力例: 2024年2月20日火曜日 15時30分45秒主なオプション一覧
- year: 年の表示('numeric', '2-digit')
- month: 月の表示('numeric', '2-digit', 'long', 'short', 'narrow')
- day: 日の表示('numeric', '2-digit')
- weekday: 曜日の表示('long', 'short', 'narrow')
- hour: 時の表示('numeric', '2-digit')
- minute: 分の表示('numeric', '2-digit')
- second: 秒の表示('numeric', '2-digit')
実践的な使用例
年月日のみの表示
const dateFormatter = new Intl.DateTimeFormat('ja-JP', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
console.log(dateFormatter.format(date));
// 出力例: 2024年2月20日時刻のみの表示
const timeFormatter = new Intl.DateTimeFormat('ja-JP', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log(timeFormatter.format(date));
// 出力例: 15:30:45異なるロケールでの表示
// 英語(アメリカ)
const usFormatter = new Intl.DateTimeFormat('en-US');
console.log(usFormatter.format(date));
// 出力例: 2/20/2024
// フランス語
const frFormatter = new Intl.DateTimeFormat('fr-FR');
console.log(frFormatter.format(date));
// 出力例: 20/02/2024エラー対処法
よくあるエラーと解決策
1. RangeError: invalid language tag
// 誤った使用
const formatter = new Intl.DateTimeFormat('invalid');
// 正しい使用
const formatter = new Intl.DateTimeFormat('ja-JP');2. TypeError: date is not valid
// 誤った使用
const formatter = new Intl.DateTimeFormat('ja-JP');
formatter.format('2024-02-20');
// 正しい使用
const formatter = new Intl.DateTimeFormat('ja-JP');
formatter.format(new Date('2024-02-20'));`Intl.DateTimeFormat()`を使用することで、JavaScriptでの日付フォーマットが簡単に実装できます。ブラウザの互換性も優れており、現代のWebアプリケーション開発において推奨される方法です。
参考:
- MDN Web Docs
- ECMAScript Internationalization API
- JavaScript Date オブジェクトのドキュメント