Age Last Birthday
There are all sorts of different processes that some people use to calculate someone's age from their date of birth using JavaScript. Some are complicated involving calculations directly on the component parts of the dates while others try to simplify things by using date objects and end up being inaccurate when it is close to the person's birthday.
With this method that can be added to the JavaScript date object I have tried to keep things as simple as possible while making sure that the value returned is accurate (even on the person's birthday and the day before). Since two dates are involved I decided that the date where the method will be used will be the date you want their age on and their date of birth date object will be passed to the method as a parameter. The code I ended up with is:
var cy = this.getFullYear();
var by = dob.getFullYear();
var db = new Date(dob);
db.setFullYear(cy);
var adj = (this-db<0) ? 1 : 0;
return cy - by - adj;
}
Basically the code subtracts the year of their birth from the current year and adjusts by one year if the current date is before their birthday this year. You can't get much simpler with the calculation than that and it is accurate as to when the person's birthday falls (unlike just subtracting one date from the other where you have the problem of just exactly how many days there are in a year).
So how do you use it? Well the first thing to do is to make sure that both dates are actually in date objects. So if a person was born on 2nd January 1920 and we want to know their age now we'd set the dates like this (remembering to subtract one from the month).
var dob = new Date(1920, 0, 2);
We can then reference their current age anywhere in the code using today.ageLastBirthday(dob) which will return a numeric value that is exactly how old they are today. You can of course substitute whatever dates you want for dob and today in order to get a person's age on any date you like.
Just to finish it off with a working example as usual I'll let you in on a secret. I turned on my last birthday (I was born a little more recently than the 1920 of my earlier example).

