JavaScript:入力された年月日が妥当な日付かを判別する関数

JavaScript:入力された年月日が妥当な日付かを判別する関数

たまにこのコードが欲しくて過去のコードを漁るときがあるためここに載せておきます。

関数 #

指定された年月日が実在する日付なのかを判別する関数です。

const isValidDate = (year, month, date) => {
  const y = Number(year);
  const m = Number(month) - 1;
  const d = Number(date);
  const time = new Date(y, m, d);
  return (
    y === time.getFullYear() && m === time.getMonth() && d === time.getDate()
  );
};

説明 #

原理は簡単です。渡された年月日(A)を用いて Date オブジェクトを生成します。その後、生成された Date オブジェクトの持つ年月日(B)とさきほどの年月日(A)をそれぞれ比較します。

渡された日付が妥当(実在する日付)であれば両者は一致します。逆に実在しない日付(例:2021 年 12 月 32 日)の場合は両者が一致しません。

気になる方は以下を実行していただき、関数の判定結果が正しいか確認してみてください。

const times = [
  [2021, 01, 00], // 想定:false
  [2021, 01, 01], // 想定:true
  [2021, 12, 32], // 想定:false
  [2021, 12, 31], // 想定:true
  [2021, 02, 29], // 想定:false - 2021年は閏年ではありません
  [2024, 02, 29], // 想定:true - 2024年は閏年です
];

times.forEach(([year, month, date]) => {
  console.log(isValidDate(year, month, date));
});

また、引数として受け取った year month date を関数内部で Number() で数値に変換していることで、引数が文字列だった場合も機能するようにしています。

const times = [
  ["2021", "01", "00"],
  ["2021", "01", "01"],
  ["2021", "12", "32"],
  ["2021", "12", "31"],
  ["2021", "02", "29"],
  ["2024", "02", "29"],
];

times.forEach(([year, month, date]) => {
  console.log(isValidDate(year, month, date));
});