根據datetimepicker選擇的日期計算年齡

ljw_Josie發表於2017-04-13

首先上圖看一下實現的效果:


html:(切記input加上value)

    <div class="form-group">
      <div class="col-md-4 control-label">
        <label>出生日期:</label>
      </div>
      <div class="controls col-md-5">
        <input class="form-control calendar-item" name="birthday" type="text" id="birthday" value={{ activityMember.birthday|date('Y-m-d') }} readonly="true">
        <i class="es-icon es-icon-calendar text-xlg"></i>
      </div>
      <div class="text-left color-gray">
        <span class="mlm">年齡:</span><input class="js-get-age" type="text" name="age" value=""readonly="true">      
      </div>
    </div>

js:

  $('#birthday').change(function(){
    var strBirthday = $('#birthday').val();
    $('.js-get-age').val(jsGetAge(strBirthday));
  })

  function jsGetAge(strBirthday){         
    var returnAge;  
    var strBirthdayArr=strBirthday.split("-");  
    var birthYear = strBirthdayArr[0];  
    var birthMonth = strBirthdayArr[1];  
    var birthDay = strBirthdayArr[2];  
      
    d = new Date();  
    var nowYear = d.getFullYear();  
    var nowMonth = d.getMonth() + 1;  
    var 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;//返回週歲年齡     
  }  


總結一下就是:

1,給datepicker加一個change事件;

2,執行計算年齡的function;

3,將返回的週歲數賦給要輸出的標籤裡面。






相關文章