js通过出生日期获取年龄

js通过出生日期跟当前日期对比获取年龄,代码如下,处理不完善处请见谅,谢谢~~~

 /**
  * @uses 根据生日计算年龄,年龄的格式是:2016-09-23
  * @param string birthday
  * @return string|number
  **/
 function getAge(birthday) {
   let iage = 0;
   if (!$.isNull(birthday)) {
     //获取出生日期的年月日
     let year = this.getYmd(birthday,'y');
     let month = this.getYmd(birthday, 'm');
     let day = this.getYmd(birthday, 'd');

  //获取当前时间的年月日
     let myDate = new Date();
     let now_year = myDate.getFullYear(); 
     let now_month = myDate.getMonth()+1; 
     let now_day = myDate.getDate(); 

     if (now_year > year) {
       iage = now_year - year - 1;
       if (now_month > month) {
         iage++;
       } else if (now_month == month) {
         if (now_day >= day) {
           iage++;
         }
       }
     }
   }
   return iage;
 },
 
 /**
  * @uses 根据指定日期返回你年月日,日期格式是:2016-09-23
  * @param string s 日期字符串
  * @param string type 返回的 年y 月m 日d
  * @return string|number
  **/
 function getYmd(s,type) {
   // var s = "2010-5-6";
   let a = s.split("-");
   if (a.length > 2) {
     let y = a[0];
     let m = a[1];
     let d = a[2];
     console.log('y:'+y,'m:'+m,'d:'+d)
     let returnStr = '';
     switch(type){
       case 'y':
         returnStr = y;
         break;
       case 'm':
         returnStr = m;
         break;
       case 'd':
         returnStr = d;
         break;
       default:
         returnStr = '';
         break;
     }
     return returnStr;
   }else{
     return '';
   }
 }

你可能感兴趣的:(js,javascript)