How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date()
function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
I have a pretty answer although it's not my code. Unfortunately I forgot the original post.
I would go for readability:
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also
@Naveens post
, is probably the most accurate, as it doesn't rely on the time of day.Benchmarks: http://jsperf.com/birthday-calculation/15
I used this approach using logic instead of math. It's precise and quick. The parameters are the year, month and day of the person's birthday. It returns the person's age as an integer.
Yet another solution:
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution. The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000 Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace
+new Date(dateString);
with
+new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)