Birthday shown last year?

I am testing a piece of JavaScript code for a site in which I want to use it. Basically, when a page loads a function performed by my age. I do this with a set date of birth. I noticed an error when playing with the birthDate variable (I don’t know exactly why this is happening). My error occurs when the month of birth is one less than the current month, and the day is at least one more than the current day, up to the current date (for example: today, June 8, everything from June 9 to June 8 produces an error)

For the fragment, I entered the date of birth 5-9-1989. Now that you or I do the math, we both know that today is 6-8-2015. The age should be 26. But for some reason, the code pops up number 25, as shown below.

(Note: as long as the input variable birthDate of the month is less than the current month, and the day is at least one more than the current day, the error will pass the year does not matter. If the dates are later or earlier than the month - 1 and day + n (n> 0) to represent the date when the error does not occur)

Any help in finding out the cause of this error would be very helpful.

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>
Run codeHide result
+4
source share
1 answer

Simply put, the month for the function Datemust be set in the range from 0 (January) to 11 (December). Just change 5 to 4 to indicate May.

Quote from MDN :

month
An integer representing the month from 0 for January to 11 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>
Run codeHide result
+6
source

All Articles