How to get the 'age' from input type '

2019-08-24 19:24发布

My question is how to get the age from the date input type using Javascript, and show it in Html.

I want the user to be able to select his Date of Birth from the Date input type, which should then be put into the 'bday' ID that I can then use to calculate the age from and fill it in the 'resultBday' element ID.

For example:
When the user selects 'January 15th, 1990' I want it to show "24 years old" in the innerHtml.

This is what I currently have:

HTML:

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

JS:

function submitBday () {
    var Q4A = "Your birthday is: "
    var Bday = document.getElementById('bday').value;
    Q4A += Bday;

    var theBday = document.getElementById('resultBday');
    theBday.innerHTML = Q4A;
}

1条回答
Deceive 欺骗
2楼-- · 2019-08-24 20:10
function submitBday() {
    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;
}

jsFiddle example

查看更多
登录 后发表回答