0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで日付を「YYYY-MM-DD」形式にフォーマットする

Posted at

JavaScript で現在の日付を「2024-12-25」のような形式で取得したい場面が多いので、
自分用メモでまとめました。シンプルな日付フォーマット方法です。

コード例

const currentDate = new Date()
  .toLocaleString("ja-JP", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  })
  .replace(/\//g, "-");

console.log(currentDate); // 出力例: "2024-12-25"

コードの解説

1. 現在日時の取得

new Date();

現在の日時を取得します。

2. 日本のロケールでフォーマット

.toLocaleString('ja-JP', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
})
  • 'ja-JP': 日本のロケールを指定
  • year: 'numeric': 年を 4 桁で表示(例:2024)
  • month: '2-digit': 月を 2 桁で表示(例:01, 12)
  • day: '2-digit': 日を 2 桁で表示(例:01, 25)

この時点では「2024/12/25」のような形式になります。

3. スラッシュをハイフンに置換

.replace(/\//g, '-')

スラッシュ(/)をハイフン(-)に置換して、最終的に「2024-12-25」形式にします。

実用的な使用例

ファイル名生成

const filename = `report_${currentDate}.csv`;
// 結果: "report_2024-12-25.csv"

ログ出力

console.log(`[${currentDate}] 処理が開始されました`);
// 結果: "[2024-12-25] 処理が開始されました"

API 通信

const response = await fetch(`/api/data?date=${currentDate}`);

フォーム入力のデフォルト値

<input type="date" defaultValue={currentDate} />

他の方法との比較

ISO 文字列を使用する方法

const currentDate = new Date().toISOString().split("T")[0];
// 結果: "2024-12-25"

こちらの方法もシンプルですが、タイムゾーンの影響を受ける可能性があります。

手動でフォーマットする方法

const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const currentDate = `${year}-${month}-${day}`;

より細かい制御が可能ですが、コードが長くなります。

まとめ

toLocaleString()を使用した方法は、読みやすく、タイムゾーンの考慮もされているため、多くの場面で安全に使用できます。

日付フォーマットは頻繁に使用する処理なので、このタイミングで整理しようと思い、
claudeさんに聞きながらメモしました。

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?