JavaScriptの Date オブジェクトを使用した、現在日時の取得とフォーマット方法のまとめです。
1. Dateオブジェクトの基本
new Date() でインスタンスを作成し、各メソッドでパーツを取得します。
const now = new Date();
const year = now.getFullYear(); // 年 (4桁)
const month = now.getMonth() + 1; // 月 (0-11なので +1 が必要)
const date = now.getDate(); // 日
const dayId = now.getDay(); // 曜日ID (0:日, 1:月...)
2. 日付フォーマット
toLocaleDateString メソッドで、日付をフォーマット
-
YYYY-MM-DD形式
const formattedDate = now.toLocaleDateString('sv-SE');※
sv-SEはスウェーデン語の短縮形で、2026-04-07のような形式でフォーマットしてくれる。 -
YYYY/MM/DD形式
const formattedDate = now.toLocaleDateString('ja-JP');※
ja-JPは日本語の短縮形で、2026/4/7のような形式でフォーマット。 -
YYYY年MM月DD日(W)形式
const formattedDate = now.toLocaleDateString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'short', });※
toLocaleDateStringはオプションを指定することで、フォーマットを変更できる。この場合、2026年4月7日(火)のような形式でフォーマット。