javascript 如何使用 html 和 js 从输入类型“日期”中获取“年龄”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21336881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the 'age' from input type 'date' using html & js?
提问by Kill22pro
My question is how to get the age from the date input type using Javascript, and show it in Html.
我的问题是如何使用Javascript从日期输入类型中获取年龄,并在Html中显示。
I want the user to be able to select his Date of Birthfrom the Dateinput 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.
我希望用户能够从Date输入类型中选择他的出生日期,然后应该将其放入“bday” ID 中,然后我可以使用它来计算年龄并将其填充到“resultBday”元素 ID 中.
For example:
When the user selects 'January 15th, 1990' I want it to show "24 years old" in the innerHtml.
例如:
当用户选择“1990 年 1 月 15 日”时,我希望它在 innerHtml 中显示“24 岁”。
This is what I currently have:
这是我目前拥有的:
HTML:
HTML:
<p id="resultBday"></p>
<input type="date" name="bday" id="bday" onchange="submitBday()">
JS:
JS:
function submitBday () {
var Q4A = "Your birthday is: "
var Bday = document.getElementById('bday').value;
Q4A += Bday;
var theBday = document.getElementById('resultBday');
theBday.innerHTML = Q4A;
}
回答by j08691
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;
}