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

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

javascriptで、日付が本日であるかを判定するサンプルコードを記述してます。今日の日付を取得して比較することで判定することができます。2パターンの方法を記述しており、後述しているやり方の方がパファーマンスは良いです。

環境

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

日付が本日であるかを判定

日付が本日であるかを判定するには、「new Date()」で本日の日付を取得して「toDateString」で日付のみを文字列に変換して比較します。

function isToday(date) {

  // 本日の日付
  const today = new Date();

  // 比較する日付を表示
  console.log(date.toDateString());

  // 本日と同じであれば「true」を返す
  if (today.toDateString() === date.toDateString()) return true;

  return false;

}

console.log(isToday(new Date())); // true
console.log(isToday(new Date('2022-12-25'))); // false

実行結果

「年月日」を、それぞれ比較して判定することも可能です。

function isToday(date) {

  const today = new Date();  

  if (today.getFullYear() === date.getFullYear() &&
    today.getMonth() === date.getMonth() &&
    today.getDate() === date.getDate()) return true;

  return false;

}

console.log(isToday(new Date())); // true
console.log(isToday(new Date('2022-12-25'))); // false

パフォーマンスは「年月日」をそれぞれ比較した方が速いです。

サンプルコード

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

※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="isToday()" class="btn btn-info mt-1">
      取得
    </button>

  </div>

  <script>    

    const isToday = () => {

      ( new Date().toDateString() === new Date(setDate.value).toDateString() ) ? result.textContent = "today" : result.textContent = "not today";

    }

  </script>
</body>

</html>

判定されていることが確認できます。