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)
var currentDate = new Date();
var age = currentDate.getFullYear() - birthDate.getFullYear();
var month = currentDate.getMonth() - birthDate.getMonth();
var day = currentDate.getDate() - birthDate.getDate();
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
source
share