美文网首页
js方法实现通过出生日期获取周岁年龄

js方法实现通过出生日期获取周岁年龄

作者: 阿羡吖 | 来源:发表于2021-08-18 09:13 被阅读0次

    /**
    strBirthday:指的是出生日期 格式为:"1990-01-01"
    */

    function GetAge(strBirthday){
      var returnAge,
      strBirthdayArr=strBirthday.split("-"),
      birthYear = strBirthdayArr[0],
      birthMonth = strBirthdayArr[1],
      birthDay = strBirthdayArr[2],  
      d = new Date(),
      nowYear = d.getFullYear(),
      nowMonth = d.getMonth() + 1,
      nowDay = d.getDate();
      if(nowYear == birthYear){
          returnAge = 0;//同年 则为0周岁
       }
      else{
         var ageDiff = nowYear - birthYear ; //年之差
         if(ageDiff > 0){
          if(nowMonth == birthMonth) {
           var dayDiff = nowDay - birthDay;//日之差
            if(dayDiff < 0) {
               returnAge = ageDiff - 1;
             }else {
               returnAge = ageDiff;
              }
           }else {
             var monthDiff = nowMonth - birthMonth;//月之差
                if(monthDiff < 0) {
                  returnAge = ageDiff - 1;
                }
                else {
                  returnAge = ageDiff ;
                }
              }
            }else {
              returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
            }
          }
          return returnAge; // 返回周岁年龄
    }
    

    相关文章

      网友评论

          本文标题:js方法实现通过出生日期获取周岁年龄

          本文链接:https://www.haomeiwen.com/subject/vrzwbltx.html