## 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);

## Solutions/Answers:

### Solution 1:

**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.

**Benchmarks: http://jsperf.com/birthday-calculation/15**

### Solution 2:

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.

### Solution 3:

**Important: This answer doesn’t provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.**

There are no better solutions ( not in these answers anyway ). – naveen

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:

```
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
```

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! 🙂

### Solution 4:

With momentjs:

```
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
```

### Solution 5:

Some time ago I made a function with that purpose:

```
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
```

It takes a Date object as input, so you need to parse the `'YYYYMMDD'`

formatted date string:

```
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
```

### Solution 6:

**Clean one-liner solution ES6 written:**

```
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// (today is 2018-06-13)
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
```

Using a year of 365.25 days (because leap years)