javascript 日付が過去であるかを判定する

javascript 日付が過去であるかを判定する

javascriptで、日付が過去であるかを判定するサンプルコードを記述してます。

環境

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

日付が過去であるかを判定

日付が過去であるかを判定するには、現在日付を取得して時間を「0時0分0秒」にして比較します。

function check(date) {

  const today = new Date();

  // 「0時0分0秒」に設定
  today.setHours(0, 0, 0, 0);

  return date < today;

}

console.log( new Date() ); // Thu Oct 13 2022 09:51:22 GMT+0900 (日本標準時)

console.log( check(new Date()) ); // false

console.log(check(new Date('2022-10-14'))); // false

console.log(check(new Date('2022-10-12'))); // true

サンプルコード

以下は、
「比較」ボタンをクリックして、フォームから取得した日付が本日より過去であるかを判定した結果を表示する
サンプルコードとなります。

※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 class="badge badge-success">結果</span></h2>
    <h2><span class="badge badge-success">現在日付</span></h2>

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

    <button type="button" onclick="hoge()" class="btn btn-success mt-1">
      比較
    </button>

  </div>

  <script>

    function hoge() {

      // フォームの入力を取得
      let value = document.getElementById('date1').value;

      // 表示用要素取得
      let result = document.getElementsByClassName("badge")[0];

      if (value === "") {
        result.textContent = "日付が未入力です";
        return;
      } else {
        // date型に変換
        let date = new Date(value);
      }

      // 現在日付を表示
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();

      let today = year + '年' + month + '月' + day + '日';

      let time = document.getElementsByClassName("badge")[1];
      time.textContent = today;

      // 判定
      if (date.getTime() < new Date().setHours(0, 0, 0, 0)) {
        result.textContent = "過去です";
      } else {
        result.textContent = "未来です";
      }

    }

  </script>
</body>

</html>

結果が表示されていることが確認できます。