JavaScript 逆引き集 | Intl.DateTimeFormat の利用

JavaScript JavaScript
スポンサーリンク

Intl.DateTimeFormat の基本と実践

Intl.DateTimeFormat はロケールやタイムゾーンに合わせた日付・時刻フォーマットを簡単に行える標準APIです。文字列連結や手作業のゼロ埋めから卒業して、読みやすく一貫した表示ができます。


構文と基本ポイント

// もっとも基本的な使い方
const d = new Date();
const fmt = new Intl.DateTimeFormat("ja-JP");
console.log(fmt.format(d)); // 例: "2025/12/05"
JavaScript
  • ロケール: “ja-JP” のように言語・地域を指定。省略時は環境のデフォルトロケールが使われます。
  • 返り値: 指定ロケールの慣習に基づく整形済み文字列。Date自体は変わりません。

すぐ使えるテンプレート集

日本語の標準日付表示

const d = new Date();
console.log(new Intl.DateTimeFormat("ja-JP").format(d));
// 例: "2025/12/05"
JavaScript
  • ポイント: ロケールを指定するだけで、その地域の標準的な並びと区切りに整形されます。

dateStyle / timeStyle で簡易プリセット

const d = new Date();
console.log(new Intl.DateTimeFormat("ja-JP", { dateStyle: "full" }).format(d));
// 例: "2025年12月5日金曜日"
console.log(new Intl.DateTimeFormat("ja-JP", { dateStyle: "medium", timeStyle: "short" }).format(d));
// 例: "2025/12/5 9:47"
JavaScript
  • ポイント: dateStyle と timeStyle(”full” | “long” | “medium” | “short”)でまとめて指定。細かいオプション指定より手軽です。

カスタム書式(年・月・日・時など個別指定)

const d = new Date();
const fmt = new Intl.DateTimeFormat("ja-JP", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
});
console.log(fmt.format(d)); // 例: "2025/12/05 09:47:00"
JavaScript
  • ポイント: “numeric” / “2-digit”などでゼロ埋めや桁を制御できます。柔軟な整形が可能です。

タイムゾーンを明示して表示(例: 東京時間)

const d = new Date(); // どこで実行しても
const tokyo = new Intl.DateTimeFormat("ja-JP", {
  timeZone: "Asia/Tokyo",
  dateStyle: "medium",
  timeStyle: "medium",
});
console.log(tokyo.format(d)); // 実行環境に依存せずJSTで表示
JavaScript
  • ポイント: timeZone を指定すると、環境のTZに依存せず狙った地域時間で表示できます。

曜日を付けて表示

const d = new Date();
const weekday = new Intl.DateTimeFormat("ja-JP", { weekday: "short" }).format(d);
const dateStr = new Intl.DateTimeFormat("ja-JP", { year: "numeric", month: "2-digit", day: "2-digit" }).format(d);
console.log(`${dateStr}${weekday})`); // 例: "2025/12/05(金)"
JavaScript
  • ポイント: weekday: “narrow” | “short” | “long” で曜日表記を選べます。漢字一文字の「narrow」も指定可能です。

実務で便利なオプション

  • タイムゾーン指定:
    • timeZone: "Asia/Tokyo" のように地域名を指定して、表示の一貫性を担保します。
  • 時刻の12/24時間制:
    • hourCycle: "h23"(24時間)や "h12"(AM/PM)で切替可能。ロケールの慣習に左右されたくない場合に便利です。
  • 部分フォーマットの分解(formatToParts):
    • ポイント: 出力をパーツに分解して、独自の並びに再構成できます。
const parts = new Intl.DateTimeFormat("ja-JP", {
  year: "numeric", month: "2-digit", day: "2-digit"
}).formatToParts(new Date());
// [{ type: 'year', value: '2025' }, { type: 'literal', value: '/' }, ...]
JavaScript
  • 暦や数字体系(上級):
    • Unicode拡張キーで和暦や別の数字体系へ切替(例: "ja-JP-u-ca-japanese""…-nu-hanidec")。ブラウザ差異があるため検証が必要です。

よくある落とし穴と対策

  • 環境ごとで表示差が出る: ロケールとTZを省略すると、ユーザー環境に依存した表示になります。
    • 対策: 仕様でロケール・タイムゾーンを明示し、Intl へ渡して固定化します。
  • AM/PM と 24時間制の混在: ロケールにより既定の時刻体系が変わります。
    • 対策: hourCycle を指定して、意図を固定します。
  • 独自レイアウトが必要: 一部だけ太字、区切りを変更など。
    • 対策: formatToParts で分解し、DOMやテンプレートで好みの構成に組み直します。
  • ライブラリ導入の迷い: ちょっとした整形のために外部ライブラリは重い。
    • 対策: Intl.DateTimeFormat でほとんどのニーズは満たせます。複雑な演算やタイムゾーン変換が多い場合のみ dayjs/date-fns/Luxon を検討。

便利な関数テンプレート

// 1) ロケール・TZ固定のフォーマッタを作る
const makeFormatter = (locale = "ja-JP", opts = {}) =>
  new Intl.DateTimeFormat(locale, { timeZone: "Asia/Tokyo", ...opts });

const fmtDate = makeFormatter("ja-JP", { dateStyle: "medium" });
const fmtDateTime = makeFormatter("ja-JP", { dateStyle: "short", timeStyle: "short" });

console.log(fmtDate.format(new Date()));     // "2025/12/05"
console.log(fmtDateTime.format(new Date())); // "2025/12/05 9:47"

// 2) 曜日付き(短縮)
const fmtWeekday = makeFormatter("ja-JP", { weekday: "short" });
console.log(fmtWeekday.format(new Date())); // "金"
JavaScript
  • ポイント: フォーマッタを使い回すのが定石。毎回オプションを書くより安全で読みやすいです。

練習問題(手を動かして覚える)

  • 1. 日本語の full スタイルで現在日時を表示
console.log(new Intl.DateTimeFormat("ja-JP", { dateStyle: "full", timeStyle: "long" }).format(new Date()));
JavaScript
  • 2. 東京時間で “YYYY/MM/DD HH:mm:ss” 相当の表示
const fmt = new Intl.DateTimeFormat("ja-JP", {
  timeZone: "Asia/Tokyo",
  year: "numeric", month: "2-digit", day: "2-digit",
  hour: "2-digit", minute: "2-digit", second: "2-digit",
  hourCycle: "h23",
});
console.log(fmt.format(new Date()));
JavaScript
  • 3. formatToParts でパーツを取得して独自組み立て
const d = new Date();
const parts = new Intl.DateTimeFormat("ja-JP", { year:"numeric", month:"2-digit", day:"2-digit" }).formatToParts(d);
const get = t => parts.find(p => p.type === t)?.value;
console.log(`${get("year")}-${get("month")}-${get("day")}`); // "2025-12-05"
JavaScript

直感的な指針

  • まずはロケールとTZを固定: 表示のブレをなくす。
  • 簡単に整えるなら dateStyle/timeStyle: すぐに実用的な書式に。
  • 細かな制御は個別オプション+hourCycle: 桁やAM/PMを明確化。
  • 独自レイアウトは formatToParts: パーツを拾って自由に組み替える。

仕様・オプション一覧や動作例は MDN の Intl.DateTimeFormat ドキュメントが網羅的です。日本語の記事やチュートリアルも実務のヒントになります。

タイトルとURLをコピーしました