0
0

TypeScript - カレンダー日付の妥当性確認(2)

Posted at

FullCalendarライブラリで日付の移動をするときに、2/31や4/31などカレンダー上存在しない日付であるかチェックをする関数をどうやって実装するか調べました。

前回記事:

■改善点
Dateオブジェクトを生成するときに「new Date('1/01/41')」とすると、2041/1/1(Tue Jan 01 2041 00:00:00 GMT+0900 (日本標準時))で生成されます。
1年1月41日と解釈すると、カレンダーの日付として存在しないため、厳密なチェックをする必要があります。
厳密なチェックとして、文字数のチェックや正規化を使ったカレンダーの日付の範囲であるかのチェックを関数に加えてみました。

■関数

sample1.ts
// 引数は、年・月・日の3つ
// 戻り値は、true:カレンダー日付として存在、false:カレンダー日付として存在しない
const isValidCalendarDate = (year: string | number, month: string | number, day: string | number): boolean => {
      // 文字列の長さを確認
      let yearLength: number
      let monthLength: number
      let dayLength: number
      if (typeof year == 'number') {
        yearLength = year.toString().length
      } else {
        yearLength = year.length
      }
      if (typeof month == 'number') {
        monthLength = month.toString().length
      } else {
        monthLength = month.length
      }
      if (typeof day == 'number') {
        dayLength = day.toString().length
      } else {
        dayLength = day.length
      }
      // 年:4文字 月:2文字 日:2文字 よりも多い文字数であれば日付として妥当でないとする
      if (yearLength > 4 || monthLength > 2 || dayLength > 2) {
        return false
      }
      //正規表現として形式を確認
      const regex = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
      const yyyyHMmHDd = year + '-' + ('00' + month).slice(-2) + '-' + ('00' + day).slice(-2)
      if (regex.test(yyyyHMmHDd) != true) {
        return false
      }
      // 日付として妥当性があるか確認
      const checkDate = new Date(yyyyHMmHDd)
      if (checkDate && ('00' + (checkDate.getMonth() + 1).toString()).slice(-2) == ('00' + month).slice(-2)){
        return true
      }
      
      return false
}

年は4桁であるという正規表現を使ったので3桁の年を引数として渡すとfalseが返ってきます。
百年単位のカレンダーを表示する場合は注意したいと思いました。

0
0
2

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
0