我的问题是如何使用Javascript从日期输入类型中获取年龄,并在Html中显示。
我希望用户能够从日期输入类型中选择出生日期,然后将其输入到我可以使用的“bday”ID中然后用来计算年龄,并将其填入'resultBday'元素ID。
例如:
当用户选择“1990年1月15日”时,我希望它在innerHtml中显示“24岁”。
这就是我目前所拥有的:
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;
}
答案 0 :(得分:4)
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;
}
答案 1 :(得分:1)
一种简单的计算年份和月份的方法如下:
HTML:
<label>Your Date of Birth <label>
<input type="date" name="birthday" id='birthday' onchange="ageCount()">
<p id="demo">age shows here</p>
JavaScript
<script>
function ageCount() {
var now =new Date(); //getting current date
var currentY= now.getFullYear(); //extracting year from the date
var currentM= now.getMonth(); //extracting month from the date
var dobget =document.getElementById("birthday").value; //getting user input
var dob= new Date(dobget); //formatting input as date
var prevY= dob.getFullYear(); //extracting year from input date
var prevM= dob.getMonth(); //extracting month from input date
var ageY =currentY - prevY;
var ageM =Math.abs(currentM- prevM); //converting any negative value to positive
document.getElementById('demo').innerHTML = ageY +' years ' + ageM +' months';
}
</script>