2015-06-08 34 views
4

我测试JavaScript片段出去的地盘我想使用它,基本上在页面加载时我的年龄执行功能。我正在设定一个出生日期。我在使用birthDate变量时发现了一个错误(不确定它究竟发生了什么)。我的错误当生日月份比当月少一个,和日比当天一路当前日期(出更大的至少一个发生的事情:今天的日期6月8日,任何事情从5月9日至六月八日产生错误)生日显示为上一年的年龄?

对于片段我进入了出生日期1989年5月9日。现在,当你或我做数学时,我们都知道基于今天的日期6-8-2015。年龄应该是26岁。但由于某种原因,代码吐出了25个数字,如下所示。 (注意:只要月份的birthDate变量输入比当前月份少一个,并且日期至少比当前日期大1,那么错误会发生一年并不重要。如果日期是以后或更早然后一个月 - 1和天+ N(N> 0)呈现,不会发生错误日期)

任何弄清楚为什么这个错误是发生将大大appericated帮助。

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>

回答

6

很简单,对于Date功能月份,就是要一个范围0(一月)到11(12月)内给出。只需将5改为4即可指定May。

MDN引用:


整数值表示的月份,以0开头的1月至11月进行。

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>

+1

谢谢你的解释。我想我的大脑并没有考虑到它最初可能被视为一个数组的事实。但现在它是有道理的 – Nalani