LoginSignup
0
1

More than 5 years have passed since last update.

日付のチェック(フォーマットと閏年)

Posted at

忘れないように

checkDate.ts
const checkDAte = (dateStr: string): string => {
  // リテラルの方が早いらしい
  // 2019-10-15のフォーマットの場合
  const reg_date = /^\d{4}-\d{1,2}-\d{1,2}$/.test(dateStr)
  if (!reg_date) {
    return 'invalid'
  }
  const parts = dateStr.split('-');
  const year = parseInt(parts[0], 10);
  const month = parseInt(parts[1], 10);
  const day = parseInt(parts[2], 10);
  const monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  // 閏年を考慮
  if (year % 400 === 0 || (year % 100 !== 0 && year % 4 ===0)) {
    monthLength[1] = 29;
  }
  if (!(day > 0 && day <= monthLength[month - 1])) {
    return 'invalid'
  }
  return 'valid'
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1