okay, so we’ve got one of our Date objects.
var d = new Date("October 23, 1992 00:00:00");
For the sake of sanity, we also have today’s date from elsewhere in the script:
var today = new Date()
We know that we can get the year, as you showed in the OP:
var year = today.getFullYear()
The page on get functions tells you that this returns a 4 digit number.
So, get the year from our birthday object;
var byear = d.getFullYear();
the difference in those values, then is:
var dyear = year - byear;
(Year should always be greater than byear, unless you were born in the future, so we know that this value is positive.)
But, we need to do more, because we dont know about the month and day yet. You should get a different answer if today is in September than you do if it’s November, because you’ve had a birthday.
So, back to the method page, which tells us we can get a month from our objects, and the day too, which we’ll need later.
var month = today.getMonth();
var bmonth = d.getMonth();
var day = today.getDate();
var bday = d.getDate();
We then check to see if the current month is less than the target month: if it is, we subtract 1.
if(month < bmonth) {
dyear--;
}
but we’re STILL not done, because if it’s the same month, we need to check the day to do a comparrison there, too…
else if(month == bmonth && day < bday) {
dyear--;
}
At this point, dyear is the numerical value of the number of years between the two dates.
If i was doing this in actual code rather than in explanation form, i wouldnt declare all those vars, and would instead just call the functions in-situ, that is to say I would reduce this:
var d = new Date("October 23, 1992 00:00:00");
var today = new Date();
var year = today.getFullYear();
var byear = d.getFullYear();
var dyear = year - byear;
var month = today.getMonth();
var bmonth = d.getMonth();
var day = today.getDate();
var bday = d.getDate();
if(month < bmonth) {
dyear--;
}
else if(month == bmonth && day < bday) {
dyear--;
}
To this:
let d = new Date("October 23, 1992 00:00:00");
let today = new Date();
let dyear = today.getFullYear() - d.getFullYear();
if(today.getMonth() < d.getMonth()) {
dyear--;
}
else if(today.getMonth() == d.getMonth() && today.getDate() < d.getDate()) {
dyear--;
}
But yes, this is still a lot longer than doing it in a server language like PHP, as @coothead pointed out.