从“Date”HTML元素计算年龄

时间:2014-01-13 06:46:41

标签: javascript

我有一个带有“Date”元素的HTML表单和一个提交按钮。有2个功能。一个用于在“date”HTML元素中计算从出生日期开始的年龄。另一个功能是将年龄与允许的最小年龄进行比较。我需要帮助来完成它。在代码中的备注中查看我的问题。是的,我看过其他类似的问题。我想学习而不仅仅是复制/粘贴。如果我理解我的代码/语法有什么问题,那么我会更好地学习。提前谢谢。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title></title>
</head>
<body>
 <script type="text/javascript">

    var minAge = 18;

    var curDate = new Date();

    var curr_year = curDate.getFullYear();
    var curr_month = curDate.getMonth();


    //Calculates age from given Birth Date in the form//
    function _calcAge() {

        var dt1 = document.getElementById('date').value;
        var birth_date = new Date(dt1);

        var birth_year = birth_date.getFullYear();
        var birth_month = birth_date.getMonth();
        var calc_year = curr_year - birth_year;
        var calc_month = curr_month - birth_month;

        //The following below is what I am not sure about. 
        //I need to combine years and months and
        //convert them into a string??? Is this syntax dead wrong?

    var final_result = (calc_year && "." && calc_month).toString();

        // final result should be a number with a decimal point, example: 35.5
        final_result = parseFloat;

        return (final_result);
        alert(final_result);
    }

    //Compares calculated age with minimum age and acts according to rules//
    function _setAge() {

        var age = _calcAge();
        //alert("my age is " + age);
        if (age < minAge) {
            alert("You are not allowed into the site. The minimum age is 18!");
        } else

            alert("Welcome to my Site");
            window.open(main.htm, _self);

    }


    </script>

     <form>
      Date Of Birth: <input type="date" name="date of birth" id="date" />
      <input type="submit" name="submit" id="submit" onClick="_setAge();" />

     </form>

    </body>
   </html>

4 个答案:

答案 0 :(得分:3)

您可以通过基本数学函数添加或减去javascript日期。

只需为今天var Today = new Date()创建一个新日期,然后从表单中减去日期。你得到的差异在几毫秒。

现在您只需将它们除以(1000*60*60*24*365)

即可将它们转换为年/月

所以就这样做:

var difference = (curDate - birth_date)/((1000*60*60*24*365);
var differenceString = "The difference is: " + difference.toFixed(1) + " years.";

toFixed(1);以小数点后1位返回您的号码。

始终记得JavaScripts Dates Months从零开始。

你的第二个功能也应该起作用。

Here is a working fiddle

答案 1 :(得分:2)

这样就可以用这个

代替代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">

        var minAge = 18;
        function _calcAge() {
            var date = new Date(document.getElementById("date").value);
            var today = new Date();

            var timeDiff = Math.abs(today.getTime() - date.getTime());
            var age1 = Math.ceil(timeDiff / (1000 * 3600 * 24)) / 365;
            return age1;
        }
        //Compares calculated age with minimum age and acts according to rules//
        function _setAge() {

            var age = _calcAge();
            //alert("my age is " + age);
            if (age < minAge) {
                alert("You are not allowed into the site. The minimum age is 18!");
            } else

                alert("Welcome to my Site");
            window.open(main.htm, _self);

        }


    </script>
    <form>
    Date Of Birth:
    <input type="date" name="date of birth" id="date" />
    <input type="submit" name="submit" id="submit" onclick="_setAge();" />
    </form>
</body>
</html>

答案 2 :(得分:0)

我设法让它发挥作用。对于我从他那里借来的部分,我还要归功于https://stackoverflow.com/users/444991/matthttps://stackoverflow.com/a/4076440/3189118

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
     <title></title>
   </head>
     <body>
      <script type="text/javascript">

      var minAge = 18;
      var today = new Date()
      //Calculates age from given Birth Date in the form//
       function _calcAge(birthDate, givenDate) {
        givenDate = new Date(today);
        var dt1 = document.getElementById('date').value;
        var birthDate = new Date(dt1);
        var years = (givenDate.getFullYear() - birthDate.getFullYear());

        if (givenDate.getMonth() < birthDate.getMonth() ||
     givenDate.getMonth() == birthDate.getMonth() && givenDate.getDate() < birthDate.getDate()) {
            years--;
        }

        return years;
    }

    //Compares calculated age with minimum age and acts according to rules//
    function _setAge() {

        var age = _calcAge();
        if (age < minAge) {
            alert("You are not allowed into the site. The minimum age is 18!");
        } else

            alert("Welcome to my Site");


    }


</script>

<form>
    Date Of Birth: <input type="date" name="date of birth" id="date" />
    <input type="submit" name="submit" id="submit" onClick="_setAge();" />

</form>

答案 3 :(得分:0)

  

尝试一下。

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Person Details</title>
</head>

<body>
    <form>
        Birthday: <input type="date" name="bday" id="birth_date">
        <br><br>
    </form>

    <button onclick="myFunction()">view</button><br>

    <p id="age"></p>
    <script>
        function myFunction() {


            var dobString = document.getElementById("birth_date").value;
            var calculatedValue = calculate_age(dobString);

        }

        function calculate_age(dobString) {
            var diff_ms = Date.now() - Date.parse(dobString);

            var yearString = "";
            var monthString = "";
            var dayString = "";

            var yearValue = Math.floor(diff_ms / 31536000000);
            console.log("Years ", yearValue);
            var monthValue = Math.floor((diff_ms % 31536000000) / 2592000000);
            console.log("Months ", monthValue);
            var dayValue = Math.floor(((diff_ms % 31536000000) % 2592000000) / 86400000);
            console.log("Days ", dayValue);
            // var calculatedValue = yearValue + " years " + monthValue + " months " + dayValue + " days"; // calculate and execute age

            if (yearValue > 1) yearString = " years";
            else yearString = " year";
            if (monthValue > 1) monthString = " months";
            else monthString = " month";
            if (dayValue > 1) dayString = " days";
            else dayString = " day";

            if ((yearValue > 0) && (monthValue > 0) && (dayValue > 0))
                var calculatedValue = yearValue + yearString + " " + monthValue + monthString + " " + dayValue + dayString + " ";
            else if ((yearValue > 0) && (monthValue > 0) && (dayValue == 0))
                var calculatedValue = yearValue + yearString + " " + monthValue + monthString + " ";
            else if ((yearValue > 0) && (monthValue == 0) && (dayValue > 0))
                var calculatedValue = yearValue + yearString + " " + dayValue + dayString + " ";
            else if ((yearValue == 0) && (monthValue > 0) && (dayValue > 0))
                var calculatedValue = monthValue + monthString + " " + dayValue + dayString + " ";
            else if ((yearValue == 0) && (monthValue == 0) && (dayValue > 0))
                var calculatedValue = dayValue + dayString + " ";

            document.getElementById("age").innerHTML = "Age : " + calculatedValue;

        }`

    </script>`
</body>

</html>
相关问题