javascript 今月の日数を取得する

javascript 今月の日数を取得する

javascriptで、今月の日数を取得するサンプルコードを記述してます。「new Date()」で日付を「0」に指定するとその月の最終日が取得できるので、それを利用します。

環境

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

指定した月の日数を取得

指定した月の日数を取得するには、
1. 「new Date()」で日付を取得
2. 再度「new Date()」を取得した日付から月の最終日を取得(日付を0にすると最終日が取得できます)
することで可能です。

const date = new Date();

const result = new Date(date.getFullYear(), date.getMonth() + 1, 0 ).getDate();

console.log(result); // 30

サンプルコード

以下は、
「取得」ボタンをクリックすると、フォームから取得した日付の月の日数を取得して表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-50" style="margin-top:200px">

    <h2><span id="result" class="badge badge-info">結果</span></h2>

    <form>
      <div class="form-group">
        <label class="bmd-label-floating">日付</label>
        <input type="date" id="setDate">
      </div>
    </form>

    <button type="button" onclick="getDay()" class="btn btn-info mt-1">
      取得
    </button>

  </div>

  <script>    

    const getDay = () => {

      const date = new Date(setDate.value);

      result.textContent = new Date(date.getFullYear(), date.getMonth() + 1, 0 ).getDate();

    }

  </script>
</body>

</html>

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