我正在测试一个我想在其中使用它的网站的 JavaScript 片段。基本上,当页面加载我的年龄时执行的函数。我是在规定的出生日期之外做这件事的。我在使用birthDate变量时注意到一个错误(不确定为什么会发生)。当birthDate月份比当前月份小1,并且日期至少比当前日期大1一直到当前日期时,就会发生错误(例如:今天的日期6月8日,从5月9日到6月8日的任何日期都会产生错误)
对于该片段,我输入了出生日期 5-9-1989。现在,当你或我计算时,我们都知道基于今天的日期 2015 年 6 月 8 日。年龄应该是 26。但由于某种原因,代码输出了数字 25,如下所示。
(注意:只要输入的birthDate变量中的月份比当前月份小1,并且日期至少比当前日期大1,就会发生错误,年份无关紧要。如果日期晚于或早于则月 - 1 和日 + n (n > 0) 表示错误未发生的日期)
任何有助于弄清楚为什么会发生此错误的帮助将不胜感激。
function myage() {
var birthDate = new Date(1989, 5, 9, 0, 0, 0, 0)
// The current date
var currentDate = new Date();
// The age in years
var age = currentDate.getFullYear() - birthDate.getFullYear();
// Compare the months
var month = currentDate.getMonth() - birthDate.getMonth();
// Compare the days
var day = currentDate.getDate() - birthDate.getDate();
// If the date has already happened this year
if ( month < 0 || month == 0 && day < 0 || month < 0 && day < 0 )
{
age--;
}
document.write('I am ' + age + ' years old.');
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body onLoad="myage()">
</body>
</html>
很简单,这个月Date
函数的指定范围为 0(一月)到 11(十二月)。只需将 5 更改为 4 即可指定五月。
引用自MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date:
month
代表月份的整数值,从 0 开始(1 月)到 11(12 月)。
function myage() {
var birthDate = new Date(1989, 4, 9, 0, 0, 0, 0)
// The current date
var currentDate = new Date();
// The age in years
var age = currentDate.getFullYear() - birthDate.getFullYear();
// Compare the months
var month = currentDate.getMonth() - birthDate.getMonth();
// Compare the days
var day = currentDate.getDate() - birthDate.getDate();
// If the date has already happened this year
if ( month < 0 || month == 0 && day < 0 || month < 0 && day < 0 )
{
age--;
}
document.write('I am ' + age + ' years old.');
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body onLoad="myage()">
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)