日期合法校验(1.0)

isValidDate = (year, month, day) => {
  let dayAmount = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  let now = new Date()
  //校验年份
  // 年份应该是四位数字
  if (isNaN(year) || year.length !== 4) {
    return false;
  }
  // 年份应该在 1900 到 当前年 之间
  const yearNum = parseInt(year);
  let nowYear = now.getFullYear();
  if (yearNum < 1900 || yearNum > nowYear) {
    return false;
  }

  //判断是否是闰年
  if (yearNum % 4 == 0 && yearNum % 100 != 0 || yearNum % 400 == 0) {
    dayAmount[2] = 29
  }

  // 月份应该在 01 到 12 之间,并且在当月及之前
  const monthNum = parseInt(month);
  const nowMonth = now.getMonth() + 1;
  if (monthNum < 1 || monthNum > 12 || nowYear === yearNum && monthNum > nowMonth) {
    return false
  }

  //判断日是否合法
  const dayNum = parseInt(day)
  const nowDay = now.getDate()
  if (monthNum === nowMonth && dayNum > nowDay || dayNum > dayAmount[monthNum]) {
    return false
  }
  return true;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值