【JavaScript入門】日付の取得と変更

 Date オブジェクトを生成しただけでは「いつの何時か」を 見ることも変えることもできません。そこで用意されているのが get 系メソッド(取得)set 系メソッド(変更) です。
 いずれも ローカル時 (地方時)UTC の 2 系列があり、名前の前半が同じでも「返す単位」や「0 始まりか 1 始まりか」が異なるため注意が必要です。ここでは代表的なプロパティを体系化し、実践サンプルで「読み取り → 加算 → 書き戻し」の流れを体験します。

1.ローカル時を取得する get 系メソッド

メソッド返り値補足
getFullYear()4 桁年 (1999)西暦
getMonth()0‑110=1 月
getDate()1‑31
getDay()0‑60=日曜
getHours()0‑23
getMinutes()0‑59
getSeconds()0‑59
getMilliseconds()0‑999ミリ秒

UTC 系 (接頭辞 UTC)

メソッド返り値
getUTCFullYear()
getUTCMonth()0‑11
getUTCDate()1‑31
getUTCDay()0‑6
getUTCHours()0‑23
getUTCMinutes()0‑59
getUTCSeconds()0‑59
getUTCMilliseconds()0‑999

2.ローカル時を変更する set 系メソッド

メソッド引数影響
setFullYear(n)4 桁年月日を省略可
setMonth(n)0‑11月を変更
setDate(n)1‑31日を変更
setHours(n)0‑23時を変更
setMinutes(n)0‑59分を変更
setSeconds(n)0‑59秒を変更
setMilliseconds(n)0‑999ミリ秒を変更

UTC 系 (接頭辞 UTC)

 setUTCFullYear, setUTCMonth, … と続き、引数・戻り値はローカル版と同じですが「UTC ベース」で解釈されます。

3.実践サンプル ― 未来の日付をワンクリックで加算

ファイル名: date_incrementer.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>日付の取得と変更デモ</title>
<style>
body{font-family:sans-serif;margin:2rem}
button{margin-top:1rem;padding:.4rem .8rem}
pre{background:#f4f4f4;padding:.8rem}
</style>
</head>
<body>
<h2>📅 日付の取得と変更</h2>
<p id="now"></p>
<button id="add">1 年 + 1 月 + 1 日 進める</button>
<pre id="log"></pre>

<script>
(() => {
  const base = new Date(2030, 0, 1, 0, 0, 0); // 2030‑01‑01 00:00:00 JST
  const nowP = document.getElementById('now');
  const log  = document.getElementById('log');

  // 現在値を表示
  function show(d) {
    nowP.textContent =
      `現在値 (ISO): ${d.toISOString()}  /  ローカル: ${d.toLocaleString('ja-JP')}`;
  }
  show(base);

  // クリックで 1‑1‑1 進める
  document.getElementById('add').onclick = () => {
    // 取得
    const y = base.getFullYear();
    const m = base.getMonth();     // 0‑11
    const da = base.getDate();

    // 変更
    base.setFullYear(y + 1);
    base.setMonth(m + 1);          // 月は 0‑11 なので +1 で 1 月進む
    base.setDate(da + 1);

    // ログ出力
    log.textContent += `→ ${base.toLocaleString('ja-JP')} (月=${base.getMonth()+1})\n`;
    show(base);
  };
})();
</script>
</body>
</html>

ブラウザ表示例

  1. ページ読み込み直後
    現在値 (ISO): 2029‑12‑31T15:00:00.000Z / ローカル: 2030/1/1 0:00:00
  2. ボタンを押すたびに
    → 2031/2/2 0:00:00 (月=2)
    → 2032/3/3 0:00:00 (月=3) … と加算されていく

プログラム解説

ポイント
new Date(2030, 0, 1…)月は 0‑11。1 月を示すため 0 を指定
getMonth() +1 表示日本語表示では 1‑12 月なので +1
setMonth(m+1)月を 1 進める。31 日 → 2 月の場合なども自動補正
toISOString()UTC で確認用、ローカルとの差が分かる

4.実用 Tips

  1. 月と曜日は 0 始まり: ユーザー入力の 1‑12 月を内部で扱うときは ‑1、表示は +1
  2. set 系は桁あふれを自動補正: 1 月 31 日に 1 月足すと 3 月 3 日になる等。
  3. 加算は get → set の組み合わせが手軽だが、期間計算が複雑な場合は Date.UTC() でミリ秒演算する方が安全。

まとめ

  • getX / setX でローカル時を直接読み書き、getUTCX / setUTCX で時差の無い値を扱う。
  • 月と曜日の 0 始まり を忘れずに、UI 入出力時に ±1 調整。
  • set 系はオーバーフローを自動補正するため「日付を丸ごと 1 年進める」などもシンプルに書ける。

 まずはサンプルを開き、Console で base.getDay() などを呼び出しながら値の変化を観察してみてください。