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.
functionmyage() {
var birthDate = newDate(1989, 4, 9, 0, 0, 0, 0)
// The current datevar currentDate = newDate();
// The age in yearsvar age = currentDate.getFullYear() - birthDate.getFullYear();
// Compare the monthsvar month = currentDate.getMonth() - birthDate.getMonth();
// Compare the daysvar day = currentDate.getDate() - birthDate.getDate();
// If the date has already happened this yearif ( month < 0 || month == 0 && day < 0 || month < 0 && day < 0 )
{
age--;
}
document.write('I am ' + age + ' years old.');
}
<!doctype html><html><head><metacharset="utf-8"><title>Untitled Document</title></head><bodyonLoad="myage()"></body></html>
Post a Comment for "Birthday Showing As Previous Year's Age?"