在javascript中检查输入的日期是否为18年和天数



我需要检查输入的日期是否大于18年我使用以下代码

today = new Date();
          birthday_val = moment(self.$el.find(".Custdb").val(), "D-MMM-YYYY").toDate();
          birthday_val_months = birthday_val.getMonth();
          birthday_val_days = birthday_val.getDay();
          age = today.getFullYear() - birthday_val.getFullYear();
          if (today.getMonth() < birthday_val_months || (today.getMonth() === birthday_val_months && today.getDay() < birthday_val_days)) {
            age--;
          }
if(age<=18)   
{Age should be greater that 18 years}

如果我选择1998年1月1日,其显示的消息年龄应大于18岁

这个稍微修改过的代码版本应该可以做到这一点:

today = new Date();
birthday_val = moment(self.$el.find(".Custdb").val(), "D-MMM-YYYY").toDate();
age = today.getFullYear() - birthday_val.getFullYear();
month = today.getMonth() - birthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < birthday_val.getDate()))   {
    age--;
}    
if(age<=18)   
{
   alert('You should be over 18 to use this site')
}

最新更新