JavaScriptのDateで月末の日付を求め、うるう年を扱う

今月の末日の日にちは、new Date(year, monthIndex + 1, 0).getDate()で求められます。yearとmonthIndexは、同じDateからgetFullYear()とgetMonth()で取得します。うるう年の2月や12月から翌年に移る場合にも対応します。

翌月の0日で月末が求まる理由

new Date(year, monthIndex, day)の月番号は1月が0、12月が11です。dayに0を指定すると、指定した月の1日から1日前に戻ります。そのため2024年3月の0日は2月29日です。12月の末日を求めるときの月番号12は、翌年の1月として扱われます。 ECMAScript · Date Constructor

const last = new Date(2024, 2, 0);
console.log(last.getFullYear(), last.getMonth() + 1, last.getDate()); // 2024 2 29

今月の末日を求める

現在の時刻は一度だけ取り出し、同じオブジェクトから年と月を取得します。これで月が切り替わる瞬間でも2つの値の基準がそろいます。このコードは実行環境のローカル時刻に基づいて今月を選びます。getDate()の結果は28~31のいずれかです。UTCで今月を選ぶ場合は、下の関数にnow.getUTCFullYear()とnow.getUTCMonth() + 1を渡します。

const now = new Date();
const year = now.getFullYear();
const monthIndex = now.getMonth();
const lastDay = new Date(year, monthIndex + 1, 0).getDate();
console.log(lastDay);

入力された年と月から末日を求める

関数は西暦1~9999年と1~12月を受け取ります。入力された月をそのまま渡すと、UTCの日付計算では翌月の月番号になります。たとえば2月を示す入力値2は3月の月番号なので、日を0にすると2月の末日になります。複数の数値を渡すnew Date()は0~99年を1900~1999年に変換しますが、setUTCFullYear()は指定した年をそのまま使います。getUTCDate()を使うと実行環境のタイムゾーンに左右されません。 ECMAScript · Date.prototype.setUTCFullYear()

function lastDayOfMonth(year, month1to12) {
  if (!Number.isInteger(year) || year < 1 || year > 9999 ||
      !Number.isInteger(month1to12) || month1to12 < 1 || month1to12 > 12) {
    throw new RangeError();
  }

  const date = new Date(0);
  date.setUTCFullYear(year, month1to12, 0);
  return date.getUTCDate();
}

console.log(lastDayOfMonth(2024, 2));  // 29
console.log(lastDayOfMonth(2023, 2));  // 28
console.log(lastDayOfMonth(2024, 12)); // 31
console.log(lastDayOfMonth(96, 2));    // 29

4で割り切れる年はうるう年です。ただし100で割り切れる年は、400でも割り切れる場合に限ります。そのため1900年2月は28日、2000年2月は29日です。西暦0096年の2月も29日です。この規則はDateの計算に組み込まれています。 ECMAScript · Day Number and Time within Day

完成したサンプルで確認する

コードをlast-day.htmlとして保存し、ブラウザーで開きます。初めはローカル時刻での年と月、および末日が表示されます。年に2024、月に2を入力して計算すると2024-02-29になります。2023年2月は2023-02-28、2024年12月は2024-12-31です。月に0や13を入力すると、ブラウザーが範囲外であることを示します。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>月末の日付を計算する</title>
</head>
<body>
<h1>月末の日付を計算する</h1>
<form id="month-form">
  <label>年 <input id="year" name="year" type="number" min="1" max="9999" step="1" required></label>
  <label>月 <input id="month" name="month" type="number" min="1" max="12" step="1" required></label>
  <button type="submit">計算</button>
</form>
<p>月末の日付 <output id="result" for="year month"></output></p>
<script>
function lastDayOfMonth(year, month1to12) {
  if (!Number.isInteger(year) || year < 1 || year > 9999 ||
      !Number.isInteger(month1to12) || month1to12 < 1 || month1to12 > 12) {
    throw new RangeError();
  }

  const date = new Date(0);
  date.setUTCFullYear(year, month1to12, 0);
  return date.getUTCDate();
}

const form = document.querySelector('#month-form');
const yearInput = form.elements.namedItem('year');
const monthInput = form.elements.namedItem('month');
const result = document.querySelector('#result');
const now = new Date();

function showLastDay() {
  const year = yearInput.valueAsNumber;
  const month = monthInput.valueAsNumber;
  const day = lastDayOfMonth(year, month);
  const pad = (value, length) => String(value).padStart(length, '0');
  result.textContent = [pad(year, 4), pad(month, 2), pad(day, 2)].join('-');
}

yearInput.value = now.getFullYear();
monthInput.value = now.getMonth() + 1;
if (form.checkValidity()) showLastDay();

form.addEventListener('submit', event => {
  event.preventDefault();
  if (form.reportValidity()) showLastDay();
});
</script>
</body>
</html>