Reputation: 397
I am testing a JavaScript snippet out for a site I want to use it in. Basically when the page loads the function my age executes. I'm doing this off a set birth-date. I noticed an error when playing with the birthDate variable (not sure exactly why it happens). My error happening when the birthDate month is one less than the current month, and the day is at least one greater than the current day all the way to the current date (Ex: Today's Date June 8th, anything from May 9th to June 8th produces the error)
For the snippet I entered the birth date 5-9-1989. Now when you or I do the math we both know that based on today's date 6-8-2015. The age should be 26. But for some reason the code spits out the number 25 as demonstrated below.
(Note: as long as the birthDate variable input of month is one less than the current month, and the day is at least one greater than the current day the error will happen year doesn't matter. If the dates are later or earlier then month - 1 and day + n (n > 0) to present date the error doesn't occur)
Any help figuring out why this error is occuring would be greatly 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>
Upvotes: 4
Views: 130
Reputation: 12017
Quite simply, the month for the Date
function is meant to be given within a range of 0 (January) to 11 (December). Just change the 5 to a 4 to specify May.
To quote from MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.
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>
Upvotes: 5