如何通过自动填充我的表格来获取年、月和日的年龄?

How do I get age in years, months and days by auto populating my form?

我想使用日期选择器在我的表单中自动填写我的年龄。当我使用日期选择器将生日放在出生日期表单上时,它应该自动填充表单中的年龄,然后它会自动确定它的年龄。例如,我的生日是 10/17/1996,今天是 7/30/2017,所以表格会像这样自动填充: 20年9个月13天

<!--html form-->
<input type="date" name="birthday"> 10/17/1996
<input type="text" name="Years"> 20 years
<input type="text" name="m"> 9 months
<input type="text" name="d"> 13 days

<!--script right here-->
function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var Years = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        Years--;
    }
    return Years;
}

你可以像下面那样做:-

$(document).ready(function(){
  $('input[type="date"]').on('mouseout',function(){
    getAge($(this).val());
  });

});
function getAge(dateString) {
  if(dateString!==''){
    d1 = new Date();
    d2 = new Date(dateString);
    diff = new Date(
        d1.getFullYear()-d2.getFullYear(), 
        d1.getMonth()-d2.getMonth(), 
        d1.getDate()-d2.getDate()
    );
    
    $('input[name="Years"]').val(diff.getYear()+" Year(s)");
    $('input[name="m"]').val(diff.getMonth()+" Month(s)");
    $('input[name="d"]').val(diff.getDate()+" Day(s)");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="birthday"><br/><br/>
<input type="text" name="Years"><br>
<input type="text" name="m"><br>
<input type="text" name="d"><br>