日付・時間の処理
Date Intl.DateTimeFormat Temporal
日付・時刻の取得・フォーマット・計算処理をまとめます。
デモ:現在時刻(1秒ごと更新)
09:10:55
ISO形式
2026-04-08T09:10:55.678Z
日本語(日付)
2026年4月8日(水)
英語(米国)
Wednesday, April 8, 2026
Unix Timestamp
1775639455
UTC文字列
Wed, 08 Apr 2026 09:10:55 GMT
ロケール
2026/4/8 9:10:55
コード例:Date オブジェクト
js
// 現在時刻
const now = new Date();
Date.now(); // Unixタイムスタンプ(ms)
// 日付の生成
new Date(2024, 0, 15); // 2024/01/15(月は0始まり!)
new Date("2024-01-15"); // ISO文字列から
new Date(1705276800000); // タイムスタンプから
// コンポーネントの取得
now.getFullYear(); // 年(4桁)
now.getMonth(); // 月(0〜11!0=1月)
now.getMonth() + 1; // 表示用の月
now.getDate(); // 日(1〜31)
now.getDay(); // 曜日(0=日曜)
now.getHours(); // 時(0〜23)
now.getMinutes(); // 分
now.getSeconds(); // 秒
now.getTime(); // タイムスタンプ(ms)
// 日付の計算
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1); // 翌日
// 日付の差を計算(日数)
const d1 = new Date("2024-01-01");
const d2 = new Date("2024-12-31");
const diffDays = Math.round((d2 - d1) / (1000 * 60 * 60 * 24)); // 365
// Intl.DateTimeFormat:ロケール対応フォーマット
const fmt = new Intl.DateTimeFormat('ja-JP', {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
});
fmt.format(now); // "2024年1月15日(月) 10:30"
// dateStyle / timeStyle(シンプル版)
new Intl.DateTimeFormat('ja-JP', {
dateStyle: 'full', // "full" | "long" | "medium" | "short"
timeStyle: 'short',
}).format(now);⚠️ Date の落とし穴
js
// 月は 0始まり(0 = 1月)
new Date(2024, 0, 15); // 1月15日
new Date(2024, 11, 31); // 12月31日
// タイムゾーンに注意
new Date("2024-01-15"); // UTC として解釈
new Date("2024-01-15T00:00:00"); // ローカル時間として解釈
// Date.now() vs new Date()
Date.now(); // 高速(タイムスタンプのみ)
new Date().getTime(); // 同じ値だが遅いNEWTemporal API(次世代日付APIプロポーザル)
Date の多くの問題(0始まり月、タイムゾーン、ミュータブルなど)を解決する新しい日付APIです。 現在はポリフィルで利用可能です。
js
// Temporal API(ステージ3プロポーザル)
// ポリフィル: npm install @js-temporal/polyfill
import { Temporal } from '@js-temporal/polyfill';
// 現在の日付(タイムゾーン考慮)
const today = Temporal.Now.plainDateISO(); // 2024-01-15
const now = Temporal.Now.zonedDateTimeISO(); // タイムゾーン付き
// 月は1始まり!
const date = Temporal.PlainDate.from({ year: 2024, month: 1, day: 15 });
// 日付計算(シンプル)
date.add({ months: 3 }); // 3ヶ月後
date.until({ year: 2025, month: 1, day: 1 }); // 日付差
// イミュータブル(元のオブジェクトは変更されない)
const tomorrow = date.add({ days: 1 }); // 新しいオブジェクト🤖 AIプロンプトテンプレート
以下の要件を満たすTypeScript + Reactコンポーネントを作成してください。 - DateオブジェクトとIntl.DateTimeFormatを使った日付・時刻処理のサンプルを示す - 日付のフォーマット(年月日・時分秒)を日本語ロケールで表示する例を含める - 2つの日付の差分(日数・時間)を計算するサンプルを含める - タイムゾーンを指定した日時変換の例を示す - Temporal APIを使ったモダンな日付操作のサンプルを含める - コメントは日本語で記述する
⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。