首页 > 代码库 > js根据生日计算出年龄

js根据生日计算出年龄

  1. /*根据出生日期算出年龄*/  
  2. function jsGetAge(strBirthday){         
  3.     var returnAge;  
  4.     var strBirthdayArr=strBirthday.split("-");  
  5.     var birthYear = strBirthdayArr[0];  
  6.     var birthMonth = strBirthdayArr[1];  
  7.     var birthDay = strBirthdayArr[2];  
  8.       
  9.     d = new Date();  
  10.     var nowYear = d.getFullYear();  
  11.     var nowMonth = d.getMonth() + 1;  
  12.     var nowDay = d.getDate();  
  13.       
  14.     if(nowYear == birthYear){  
  15.         returnAge = 0;//同年 则为0岁  
  16.     }  
  17.     else{  
  18.         var ageDiff = nowYear - birthYear ; //年之差  
  19.         if(ageDiff > 0){  
  20.             if(nowMonth == birthMonth) {  
  21.                 var dayDiff = nowDay - birthDay;//日之差  
  22.                 if(dayDiff 0)  
  23.                 {  
  24.                     returnAge = ageDiff - 1;  
  25.                 }  
  26.                 else  
  27.                 {  
  28.                     returnAge = ageDiff ;  
  29.                 }  
  30.             }  
  31.             else  
  32.             {  
  33.                 var monthDiff = nowMonth - birthMonth;//月之差  
  34.                 if(monthDiff 0)  
  35.                 {  
  36.                     returnAge = ageDiff - 1;  
  37.                 }  
  38.                 else  
  39.                 {  
  40.                     returnAge = ageDiff ;  
  41.                 }  
  42.             }  
  43.         }  
  44.         else  
  45.         {  
  46.             returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天  
  47.         }  
  48.     }  
  49.       
  50.     return returnAge;//返回周岁年龄  
  51.       
  52. }  

js根据生日计算出年龄