我有一个带有“日期”元素和一个提交按钮的 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>
最佳答案
您可以通过基本的数学函数添加或减去 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);
返回带小数点后一位的数字。
永远记住 JavaScript 的日期和月份是从零开始的。
你的第二个函数也应该可以工作。
关于javascript - 从 "Date"HTML 元素计算年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21085398/