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);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
Function esNumero
To test whether the birthday already passed or not, I define a helper function
Date.prototype.getDoY
, which effectively returns the day number of the year. The rest is pretty self-explanatory.Clean one-liner solution ES6 written:
Using a year of 365.25 days (because leap years)
Assuming if a person is born Sep 11 1991, he would not be 1 year old until Sep 12 1992.
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
Try this.
I believe the only thing that looked crude on your code was the
substr
part.Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/