Javascript Form How to - Get the 'age' from input type 'date'








Question

We would like to know how to get the 'age' from input type 'date'.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function submitBday() {<!--from   w w w . ja v a  2  s.  c  o m-->
    var Q4A = "Your birthday is: ";
    var Bdate = document.getElementById('bday').value;
    var Bday = +new Date(Bdate);
    Q4A += Bdate + ". You are " + ~~ ((Date.now() - Bday) / (31557600000));
    var theBday = document.getElementById('resultBday');
    theBday.innerHTML = Q4A;
}

</script>
</head>
<body>
  <p id="resultBday"></p>
  <input type="date" name="bday" id="bday" onchange="submitBday()">
</body>
</html>

The code above is rendered as follows: