javascript 日付の妥当性を判定する

javascript 日付の妥当性を判定する

javascriptで、日付の妥当性を判定するサンプルコードを記述してます。

環境

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

日付の妥当性を判定する

日付型であるかを判定するには「new Date()」でメソッドが使用できるかで判定します。

function check(date){ return !Number.isNaN(new Date(date).getDate()) };

console.log( check('2022-12-31') );
// true

console.log( check('2022/12/31') );
// true

console.log( check('2022.12.31') );
// true

console.log( check('2022 12 31') );
// true

console.log( check('2022-12-31 12:34:56') );
// true

console.log( check('a') );
// false

console.log( check('2022-12-32') );
// false

console.log( check('2022_12_31') );
// false

Date.parse

UTC(世界協定時 – 1970年1月1日 0時0分0秒)からのミリ秒の数値を返す「Date.parse」を使用して判定することもできます。

function check(date){ return !Number.isNaN(Date.parse(date)) };

console.log( check('2022-12-31') );
// true

console.log( check('2022/12/31') );
// true

console.log( check('2022.12.31') );
// true

console.log( check('2022 12 31') );
// true

console.log( check('2022-12-31 12:34:56') );
// true

console.log( check('a') );
// false

console.log( check('2022-12-32') );
// false

console.log( check('2022_12_31') );
// 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 class="badge badge-info">結果</span></h2>

    <form>
      <div class="form-group">        
        <input type="text" id="setData">
      </div>
    </form>

    <button type="button" onclick="isDate()" class="btn btn-info mt-1">
      判定
    </button>

  </div>

  <script>    

    const isDate = () => {

      let obj = document.getElementsByClassName("badge")[0];

      (!Number.isNaN(new Date(setData.value).getDate())) ? obj.textContent = '妥当' : obj.textContent = '妥当ではない';

    }

  </script>
</body>

</html>

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