Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age given the birth date in the format YYYYMMDD

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);
like image 403
Francisc Avatar asked Oct 30 '10 18:10

Francisc


People also ask

How do I calculate age from Yyyymmdd in Excel?

Type a birthdate into a cell in the format MM/DD/YYYY (if in the United States) or in the format DD/MM/YYYY if your country uses that format. Type =DATEDIF(XX, TODAY(), “Y”) then press Enter on your keyboard. Change the “XX” part of the formula to the cell containing the birthdate.

How do you calculate age from a date?

Simply by subtracting the birth date from the current date. This conventional age formula can also be used in Excel. The first part of the formula (TODAY()-B2) returns the difference between the current date and date of birth is days, and then you divide that number by 365 to get the numbers of years.

How do I calculate my age manually by date of birth?

The method of calculating age involves the comparison of a person's date of birth with the date on which the age needs to be calculated. The date of birth is subtracted from the given date, which gives the age of the person. Age = Given date - Date of birth.


2 Answers

Try this.

function getAge(dateString) {     var today = new Date();     var birthDate = new Date(dateString);     var age = today.getFullYear() - birthDate.getFullYear();     var m = today.getMonth() - birthDate.getMonth();     if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {         age--;     }     return age; } 

I believe the only thing that looked crude on your code was the substr part.

Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/

like image 185
naveen Avatar answered Sep 22 '22 06:09

naveen


I would go for readability:

function _calculateAge(birthday) { // birthday is a date     var ageDifMs = Date.now() - birthday.getTime();     var ageDate = new Date(ageDifMs); // miliseconds from epoch     return Math.abs(ageDate.getUTCFullYear() - 1970); } 

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.


like image 22
André Snede Avatar answered Sep 22 '22 06:09

André Snede