【问题标题】:How to get the 'age' from input type 'date' using html & js?如何使用 html 和 js 从输入类型“日期”中获取“年龄”?
【发布时间】:2014-02-15 16:41:41
【问题描述】:

我的问题是如何使用 Javascript 从日期输入类型中获取年龄,并以 Html 显示。

我希望用户能够从 Date 输入类型中选择他的 Date of Birth,然后将其放入我可以的“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;
}

【问题讨论】:

  • 那么问题是什么?
  • 肯定是 如何使用 html & js 从输入类型“日期”中获取“年龄”?? IE。标题?
  • 但是代码有效...
  • @Cristy - 代码只显示所选日期,不计算年龄。
  • 哦,所以问题实际上是“如何根据生日计算年龄...”

标签: javascript html date input


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    计算年月的简单方法如下:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2020-12-29
      • 2012-04-17
      相关资源
      最近更新 更多