javascript その月の全ての日付を取得する

javascript その月の全ての日付を取得する

javascriptで、その月の全ての日付を取得するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

その月の全ての日付を取得

その月の全ての日付を取得するには、ループ処理を使用することで取得できます。

function getAllDays(year, month) {

    // 最初の日付
    const date = new Date(year, month, 1);

    const dates = [];

    // 次月になるまでループさせる
    while (date.getMonth() === month) {
        // 配列に追加していく
        dates.push(new Date(date));
        date.setDate(date.getDate() + 1);
    }

    return dates;

}

const date = new Date('2024-02-24');

// 年月日形式で取得
getAllDays(date.getFullYear(), date.getMonth()).forEach(
    function (v) {
        console.log(`${v.getFullYear()}年${(v.getMonth() + 1)}月${v.getDate()}日`)
    }
)

実行結果を見ると、取得されていることが確認できます。

サンプルコード

以下は、
「取得」ボタンをクリックすると、選択した日付の月の全ての日付を取得する
サンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8" />
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<body>
  <div class="container mx-auto my-56 w-56 px-4">
    <div class="flex justify-center">
      <ul id="list" class="list-disc">
      </ul>
      <input type="date" id="date">
    </div>

    <div class="flex justify-center">
      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-purple-500 hover:border-purple-300 text-purple-500 hover:text-purple-300 font-bold py-2 px-4 rounded-full">
        取得
      </button>
    </div>
  </div>
  <script>

    // クリックイベントを登録
    btn.onclick = () => {

      // 日付を取得
      const inputDate = new Date(document.getElementById('date').value);

      const date = new Date(inputDate.getFullYear(), inputDate.getMonth(), 1);

      const dates = [];

      // 次月になるまでループさせる
      while (date.getMonth() === inputDate.getMonth()) {
        // 配列に追加していく
        dates.push('<li>' + new Date(date) + '</li>');
        date.setDate(date.getDate() + 1);
      }

      document.getElementById('list').innerHTML = dates.join('');

    }; // document.getElementById('btn');を省略

  </script>

</body>

</html>

取得されていることが確認できます。