javascript 如何使用html & js从输入类型'date'中获取'age'?

jum4pzuy  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(98)

我的问题是如何使用JavaScript从日期输入类型中获取年龄,并将其显示在HTML中。
我希望用户能够从Date输入类型中选择他的Date of Birth,然后将其放入'bday' ID中,然后我可以使用该ID计算年龄并将其填充到'resultBday'元素ID中。
举例来说:
当用户选择“January 15th,1990”时,我希望它在innerHtml中显示“24岁”。
这就是我目前所拥有的:
超文本标记语言:

<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;
}
ruoxqz4g

ruoxqz4g1#

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

bqujaahr

bqujaahr2#

计算年份和月份的简单方法如下:
超文本标记语言:

<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>
rxztt3cl

rxztt3cl3#

get ageData(){
      const today = new Date();
      const newDate = new Date(this.dateOfBirth)
      const age = today.getFullYear() - newDate.getFullYear()
      console.log(newDate.getFullYear());
      return age;
    }
    return ageDate

相关问题