Birthday Showing As Previous Year's Age?
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
Solution 1:
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>
Post a Comment for "Birthday Showing As Previous Year's Age?"