Calculate age given the birth date in the format YYYYMMDD

JavascriptDate

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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/

Solution 2 - Javascript

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.


Solution 3 - Javascript

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 - Javascript

Clean one-liner solution using ES6:

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

I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.

It has a few hours margin so depending on the use case it may not be the best option.

Solution 5 - Javascript

With momentjs:

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

Solution 6 - Javascript

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 7 - Javascript

Here's my solution, just pass in a parseable date:

function getAge(birth) {
  ageMS = Date.parse(Date()) - Date.parse(birth);
  age = new Date();
  age.setTime(ageMS);
  ageYear = age.getFullYear() - 1970;

  return ageYear;

  // ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
  // ageDay = age.getDate();    // Approximate calculation of the day part of the age
}

Solution 8 - Javascript

Alternate solution, because why not:

function calculateAgeInYears (date) {
    var now = new Date();
    var current_year = now.getFullYear();
    var year_diff = current_year - date.getFullYear();
    var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
    var has_had_birthday_this_year = (now >= birthday_this_year);

    return has_had_birthday_this_year
	    ? year_diff
	    : year_diff - 1;
}

Solution 9 - Javascript

function age()
{
    var birthdate = $j('#birthDate').val(); // in   "mm/dd/yyyy" format
    var senddate = $j('#expireDate').val(); // in   "mm/dd/yyyy" format
    var x = birthdate.split("/");    
    var y = senddate.split("/");
    var bdays = x[1];
    var bmonths = x[0];
    var byear = x[2];
    //alert(bdays);
    var sdays = y[1];
    var smonths = y[0];
    var syear = y[2];
    //alert(sdays);
    
    if(sdays < bdays)
    {
        sdays = parseInt(sdays) + 30;
        smonths = parseInt(smonths) - 1;
        //alert(sdays);
        var fdays = sdays - bdays;
        //alert(fdays);
    }
    else{
        var fdays = sdays - bdays;
    }

    if(smonths < bmonths)
    {
        smonths = parseInt(smonths) + 12;
        syear = syear - 1;
        var fmonths = smonths - bmonths;
    }
    else
    {
        var fmonths = smonths - bmonths;
    }

    var fyear = syear - byear;
    document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}

Solution 10 - Javascript

I think that could be simply like that:

function age(dateString){
    let birth = new Date(dateString);
    let now = new Date();
    let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
    return now.getFullYear() - birth.getFullYear() - beforeBirth;
}

age('09/20/1981');
//35

Works also with a timestamp

age(403501000000)
//34

Solution 11 - Javascript

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.

Date.prototype.getDoY = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.floor(((this - onejan) / 86400000) + 1);
};

function getAge(birthDate) {
	function isLeap(year) {
	    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
	}

    var now = new Date(),
	    age = now.getFullYear() - birthDate.getFullYear(),
	    doyNow = now.getDoY(),
	    doyBirth = birthDate.getDoY();

	// normalize day-of-year in leap years
	if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
		doyNow--;

	if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
		doyBirth--;

    if (doyNow <= doyBirth)
        age--;  // birthday not yet passed this year, so -1

    return age;
};
                                           
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));

Solution 12 - Javascript

I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:

var getAge = function(dob) {
    var measureDays = function(dateObj) {
            return 31*dateObj.getMonth()+dateObj.getDate();
        },
        d = new Date(dob*1000),
        now = new Date();
			
    return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}

Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.

If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.

Solution 13 - Javascript

That's the most elegant way for me:

const getAge = (birthDateString) => {
  const today = new Date();
  const birthDate = new Date(birthDateString);

  const yearsDifference = today.getFullYear() - birthDate.getFullYear();

  if (
    today.getMonth() < birthDate.getMonth() ||
    (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
  ) {
    return yearsDifference - 1;
  }

  return yearsDifference;
};

console.log(getAge('2018-03-12'));

Solution 14 - Javascript

function getAge(dateString) {

    var dates = dateString.split("-");
    var d = new Date();

    var userday = dates[0];
    var usermonth = dates[1];
    var useryear = dates[2];
	
    var curday = d.getDate();
    var curmonth = d.getMonth()+1;
    var curyear = d.getFullYear();
	
    var age = curyear - useryear;
							
    if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday   )){
	
    	age--;

    }

    return age;
}

To get the age when european date has entered:

getAge('16-03-1989')

Solution 15 - Javascript

This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?

If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:

var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)

You can get the current date formatted as YYYYMMDD like this:

var now = new Date();

var currentDate = [
	now.getFullYear(),
	('0' + (now.getMonth() + 1) ).slice(-2),
	('0' + now.getDate() ).slice(-2),
].join('');

Solution 16 - Javascript

I am a bit too late but I found this to be the simplest way to calculate a birth date.

Hopefully this will help.

function init() {
  writeYears("myage", 0, Age());

}

function Age() {
  var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
    today = new Date(),
    one_year = 1000 * 60 * 60 * 24 * 365;
  return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}

function writeYears(id, current, maximum) {
  document.getElementById(id).innerHTML = current;

  if (current < maximum) {
    setTimeout(function() {
      writeYears(id, ++current, maximum);
    }, Math.sin(current / maximum) * 200);
  }
}
init()

<span id="myage"></span>

Solution 17 - Javascript

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.

function getAge(birth) {
   var today = new Date();
   var curr_date = today.getDate();
   var curr_month = today.getMonth() + 1;
   var curr_year = today.getFullYear();

   var pieces = birth.split('/');
   var birth_date = pieces[0];
   var birth_month = pieces[1];
   var birth_year = pieces[2];
		
   if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
   if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
   if (curr_month > birth_month) return parseInt(curr_year-birth_year);
   if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
		
var age = getAge('18/01/2011');
alert(age);

Solution 18 - Javascript

Get the age (years, months and days) from the date of birth with javascript

Function calcularEdad (years, months and days)

function calcularEdad(fecha) {
        // Si la fecha es correcta, calculamos la edad

        if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
            fecha = formatDate(fecha, "yyyy-MM-dd");
        }

        var values = fecha.split("-");
        var dia = values[2];
        var mes = values[1];
        var ano = values[0];

        // cogemos los valores actuales
        var fecha_hoy = new Date();
        var ahora_ano = fecha_hoy.getYear();
        var ahora_mes = fecha_hoy.getMonth() + 1;
        var ahora_dia = fecha_hoy.getDate();

        // realizamos el calculo
        var edad = (ahora_ano + 1900) - ano;
        if (ahora_mes < mes) {
            edad--;
        }
        if ((mes == ahora_mes) && (ahora_dia < dia)) {
            edad--;
        }
        if (edad > 1900) {
            edad -= 1900;
        }

        // calculamos los meses
        var meses = 0;

        if (ahora_mes > mes && dia > ahora_dia)
            meses = ahora_mes - mes - 1;
        else if (ahora_mes > mes)
            meses = ahora_mes - mes
        if (ahora_mes < mes && dia < ahora_dia)
            meses = 12 - (mes - ahora_mes);
        else if (ahora_mes < mes)
            meses = 12 - (mes - ahora_mes + 1);
        if (ahora_mes == mes && dia > ahora_dia)
            meses = 11;

        // calculamos los dias
        var dias = 0;
        if (ahora_dia > dia)
            dias = ahora_dia - dia;
        if (ahora_dia < dia) {
            ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
            dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
        }

        return edad + " años, " + meses + " meses y " + dias + " días";
    }

Function esNumero

function esNumero(strNumber) {
    if (strNumber == null) return false;
    if (strNumber == undefined) return false;
    if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
    if (strNumber == "") return false;
    if (strNumber === "") return false;
    var psInt, psFloat;
    psInt = parseInt(strNumber);
    psFloat = parseFloat(strNumber);
    return !isNaN(strNumber) && !isNaN(psFloat);
}

Solution 19 - Javascript

One more possible solution with moment.js:

var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5

Solution 20 - Javascript

Works perfect for me, guys.

getAge(birthday) {
    const millis = Date.now() - Date.parse(birthday);
    return new Date(millis).getFullYear() - 1970;
}

Solution 21 - Javascript

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.

var getAge = function(year,month,date){
    var today = new Date();
    var dob = new Date();
    dob.setFullYear(year);
    dob.setMonth(month-1);
    dob.setDate(date);
    var timeDiff = today.valueOf() - dob.valueOf();
    var milliInDay = 24*60*60*1000;
    var noOfDays = timeDiff / milliInDay;
    var daysInYear = 365.242;
    return  ( noOfDays / daysInYear ) ;
}

Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.

Solution 22 - Javascript

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.

function calculateAge(year, month, day) {
        var currentDate = new Date();
        var currentYear = currentDate.getFullYear();
        var currentMonth = currentDate.getUTCMonth() + 1;
        var currentDay = currentDate.getUTCDate();
        // You need to treat the cases where the year, month or day hasn't arrived yet.
        var age = currentYear - year;
        if (currentMonth > month) {
            return age;
        } else {
            if (currentDay >= day) {
                return age;
            } else {
                age--;
                return age;
            }
        }
    }

Solution 23 - Javascript

Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.

I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.

/**
 * Calculates human age in years given a birth day. Optionally ageAtDate
 * can be provided to calculate age at a specific date
 *
 * @param string|Date Object birthDate
 * @param string|Date Object ageAtDate optional
 * @returns integer Age between birthday and a given date or today
 */
function gregorianAge(birthDate, ageAtDate) {
  // convert birthDate to date object if already not
  if (Object.prototype.toString.call(birthDate) !== '[object Date]')
    birthDate = new Date(birthDate);

  // use today's date if ageAtDate is not provided
  if (typeof ageAtDate == "undefined")
    ageAtDate = new Date();

  // convert ageAtDate to date object if already not
  else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
    ageAtDate = new Date(ageAtDate);

  // if conversion to date object fails return null
  if (ageAtDate == null || birthDate == null)
    return null;


  var _m = ageAtDate.getMonth() - birthDate.getMonth();

  // answer: ageAt year minus birth year less one (1) if month and day of
  // ageAt year is before month and day of birth year
  return (ageAtDate.getFullYear()) - birthDate.getFullYear() 
  - ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}

// Below is for the attached snippet

function showAge() {
  $('#age').text(gregorianAge($('#dob').val()))
}

$(function() {
  $(".datepicker").datepicker();
  showAge();
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>

Solution 24 - Javascript

Two more options:

// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
    try {
	    var d = new Date();
	    var new_d = '';
	    d.setFullYear(d.getFullYear() - Math.abs(age));
	    new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();

	    return new_d;
    } catch(err) {
	    console.log(err.message);
    }
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
    try {
	    var today = new Date();
	    var d = new Date(date);
	
	    var year = today.getFullYear() - d.getFullYear();
	    var month = today.getMonth() - d.getMonth();
	    var day = today.getDate() - d.getDate();
	    var carry = 0;

	    if (year < 0)
		    return 0;
	    if (month <= 0 && day <= 0)
		    carry -= 1;

	    var age = parseInt(year);
	    age += carry;

	    return Math.abs(age);
    } catch(err) {
	    console.log(err.message);
    }
}

Solution 25 - Javascript

I've did some updated to one previous answer.

var calculateAge = function(dob) {
    var days = function(date) {
            return 31*date.getMonth() + date.getDate();
        },
        d = new Date(dob*1000),
        now = new Date();

    return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}

I hope that helps :D

Solution 26 - Javascript

here is a simple way of calculating age:

//dob date dd/mm/yy 
var d = 01/01/1990


//today
//date today string format 
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();

//dob
//dob parsed as date format   
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();

var yearsDiff = todayYear - dobYear ;
var age;

if ( todayMonth < dobMonth ) 
 { 
  age = yearsDiff - 1; 
 }
else if ( todayMonth > dobMonth ) 
 {
  age = yearsDiff ; 
 }
    
else //if today month = dob month
 { if ( todayDate < dobDate ) 
  {
   age = yearsDiff - 1;
  }
    else 
	{
	 age = yearsDiff;
	}
 }

Solution 27 - Javascript

var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;

Solution 28 - Javascript

You may use this for age restriction in your form -

function dobvalidator(birthDateString){
	strs = birthDateString.split("-");
	var dd = strs[0];
	var mm = strs[1];
	var yy = strs[2];
	
	var d = new Date();
	var ds = d.getDate();
	var ms = d.getMonth();
	var ys = d.getFullYear();
    var accepted_age = 18;

	var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
	var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);

	if((days - age) <= '0'){
		console.log((days - age));
		alert('You are at-least ' + accepted_age);
	}else{
		console.log((days - age));
		alert('You are not at-least ' + accepted_age);
	}
}

Solution 29 - Javascript

This is my modification:

  function calculate_age(date) {
     var today = new Date();
     var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
     var age = today.getYear() - date.getYear();

     if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
       age--;
     }

    return age;
  };

Solution 30 - Javascript

I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:

function is18orOlder(dateString) {
  const dob = new Date(dateString);
  const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
  
  return dobPlus18 .valueOf() <= Date.now();
}

// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false

// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002'))  // false

I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.

Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:

 function is18orOlder(dateString) {
   const [month, date, year] = value.split('/');
   return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

Solution 31 - Javascript

Short and accurate (but not super readable):

let age = (bdate, now = new Date(), then = new Date(bdate)) => now.getFullYear() - then.getFullYear() - (now < new Date(now.getFullYear(), then.getMonth(), then.getDate()));

Solution 32 - Javascript

let dt = dob;

        let age = '';

        let bY = Number(moment(dt).format('YYYY')); 
        let bM = Number(moment(dt).format('MM')); 
        let bD = Number(moment(dt).format('DD')); 

        let tY = Number(moment().format('YYYY')); 
        let tM = Number(moment().format('MM')); 
        let tD = Number(moment().format('DD')); 


        age += (tY - bY) + ' Y ';

        if (tM < bM) {
            age += (tM - bM + 12) + ' M ';
            tY = tY - 1;
        } else {
            age += (tM - bM) + ' M '
        }

        if (tD < bD) {
            age += (tD - bD + 30) + ' D ';
            tM = tM - 1;
        } else {
            age += (tD - bD) + ' D '
        }
        
        //AGE MONTH DAYS
        console.log(age);

Solution 33 - Javascript

Here's the simplest, most accurate solution I could come up with:

Date.prototype.getAge = function (date) {
	if (!date) date = new Date();
	return ~~((date.getFullYear() + date.getMonth() / 100
	+ date.getDate() / 10000) - (this.getFullYear() + 
	this.getMonth() / 100 + this.getDate() / 10000));
}

And here is a sample that will consider Feb 29 -> Feb 28 a year.

Date.prototype.getAge = function (date) {
	if (!date) date = new Date();
	var feb = (date.getMonth() == 1 || this.getMonth() == 1);
	return ~~((date.getFullYear() + date.getMonth() / 100 + 
		(feb && date.getDate() == 29 ? 28 : date.getDate())
		/ 10000) - (this.getFullYear() + this.getMonth() / 100 + 
		(feb && this.getDate() == 29 ? 28 : this.getDate()) 
		/ 10000));
}

It even works with negative age!

Solution 34 - Javascript

Yet another solution:

/**
 * Calculate age by birth date.
 *
 * @param int birthYear Year as YYYY.
 * @param int birthMonth Month as number from 1 to 12.
 * @param int birthDay Day as number from 1 to 31.
 * @return int
 */
function getAge(birthYear, birthMonth, birthDay) {
  var today = new Date();
  var birthDate = new Date(birthYear, birthMonth-1, birthDay);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

Solution 35 - Javascript

With momentjs "fromNow" method, This allows you to work with formatted date, ie: 03/15/1968

var dob = document.getElementByID("dob"); var age = moment(dob.value).fromNow(true).replace(" years", "");

//fromNow(true) => suffix "ago" is not displayed //but we still have to get rid of "years";

As a prototype version

String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");

}

Solution 36 - Javascript

I have a pretty answer although it's not my code. Unfortunately I forgot the original post.

function calculateAge(y, m, d) {
    var _birth = parseInt("" + y + affixZero(m) + affixZero(d));
    var  today = new Date();
    var _today = parseInt("" + today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));
    return parseInt((_today - _birth) / 10000);
}
function affixZero(int) {
    if (int < 10) int = "0" + int;
    return "" + int;
}
var age = calculateAge(1980, 4, 22);
alert(age);

Solution 37 - Javascript

see this example you get full year month day information from here

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    var da = today.getDate() - birthDate.getDate();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    if(m<0){
        m +=12;
    }
    if(da<0){
        da +=30;
    }
    return age+" years "+ Math.abs(m) + "months"+ Math.abs(da) + " days";
}
alert('age: ' + getAge("1987/08/31"));    
[http://jsfiddle.net/tapos00/2g70ue5y/][1]

Solution 38 - Javascript

If you need the age in months (days are approximation):

birthDay=28;
birthMonth=7;
birthYear=1974;

var  today = new Date();
currentDay=today.getUTCDate();
currentMonth=today.getUTCMonth() + 1;
currentYear=today.getFullYear();

//calculate the age in months:
Age = (currentYear-birthYear)*12 + (currentMonth-birthMonth) + (currentDay-birthDay)/30;

Solution 39 - Javascript

Calculate age from date picker

         $('#ContentPlaceHolder1_dob').on('changeDate', function (ev) {
            $(this).datepicker('hide');

            //alert($(this).val());
            var date = formatDate($(this).val()); // ('2010/01/18') to ("1990/4/16"))
            var age = getAge(date);

            $("#ContentPlaceHolder1_age").val(age);
        });


    function formatDate(input) {
        var datePart = input.match(/\d+/g),
        year = datePart[0], // get only two digits
        month = datePart[1], day = datePart[2];
        return day + '/' + month + '/' + year;
    }

    // alert(formatDate('2010/01/18'));


    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;
    }

Solution 40 - Javascript

The below answer is the way to go if the age is just for display purposes (Might not be 100% accurate) but atleast it is easier to wrap your head around

function age(birthdate){
  return Math.floor((new Date().getTime() - new Date(birthdate).getTime()) / 3.154e+10)
}

Solution 41 - Javascript

This is my amended attempt (with a string passed in to function instead of a date object):

function calculateAge(dobString) {
    var dob = new Date(dobString);
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
    var age = currentYear - dob.getFullYear();

    if(birthdayThisYear > currentDate) {
        age--;
    }

    return age;
}

And usage:

console.log(calculateAge('1980-01-01'));

Solution 42 - Javascript

All the answers I tested here (about half) think 2000-02-29 to 2001-02-28 is zero years, when it most likely should be 1 since 2000-02-29 to 2001-03-01 is 1 year and 1 day. Here is a getYearDiff function that fixes that. It only works where d0 < d1:

function getYearDiff(d0, d1) {
    
    d1 = d1 || new Date();

    var m = d0.getMonth();
    var years = d1.getFullYear() - d0.getFullYear();

    d0.setFullYear(d0.getFullYear() + years);
    
    if (d0.getMonth() != m) d0.setDate(0);

    return d0 > d1? --years : years;
}

Solution 43 - Javascript

$("#birthday").change(function (){


var val=this.value;

var current_year=new Date().getFullYear();
if(val!=null){
	var Split = val.split("-");
	var	birth_year=parseInt(Split[2]);
	
	if(parseInt(current_year)-parseInt(birth_year)<parseInt(18)){
		
  $("#maritial_status").attr('disabled', 'disabled');
		var val2= document.getElementById("maritial_status");
    	val2.value = "Not Married";
    	$("#anniversary").attr('disabled', 'disabled');
    	var val1= document.getElementById("anniversary");
    	val1.value = "NA";
		
	}else{
		$("#maritial_status").attr('disabled', false);
		$("#anniversary").attr('disabled', false);
		
	}
}
});

Solution 44 - Javascript

function change(){
    setTimeout(function(){
        var dateObj  =      new Date();
                    var month    =      dateObj.getUTCMonth() + 1; //months from 1-12
                    var day      =      dateObj.getUTCDate();
                    var year     =      dateObj.getUTCFullYear();  
                    var newdate  =      year + "/" + month + "/" + day;
                    var entered_birthdate        =   document.getElementById('birth_dates').value;
                    var birthdate                =   new Date(entered_birthdate);
                    var birth_year               =   birthdate.getUTCFullYear();
                    var birth_month              =   birthdate.getUTCMonth() + 1;
                    var birth_date               =   birthdate.getUTCDate();
                    var age_year                =    (year-birth_year);
                    var age_month               =    (month-birth_month);
                    var age_date                =    ((day-birth_date) < 0)?(31+(day-birth_date)):(day-birth_date);
                    var test                    =    (birth_year>year)?true:((age_year===0)?((month<birth_month)?true:((month===birth_month)?(day < birth_date):false)):false) ;
                   if (test === true || (document.getElementById("birth_dates").value=== "")){
                        document.getElementById("ages").innerHTML = "";
                    }                    else{
                        var age                     =    (age_year > 1)?age_year:(   ((age_year=== 1 )&&(age_month >= 0))?age_year:((age_month < 0)?(age_month+12):((age_month > 1)?age_month:      (  ((age_month===1) && (day>birth_date) ) ? age_month:age_date)          )    )); 
                        var ages                    =    ((age===age_date)&&(age!==age_month)&&(age!==age_year))?(age_date+"days"):((((age===age_month+12)||(age===age_month)&&(age!==age_year))?(age+"months"):age_year+"years"));
                        document.getElementById("ages").innerHTML = ages;
                  }
                }, 30);

};

Solution 45 - Javascript

Try this:

$('#Datepicker').change(function(){

var $bef = $('#Datepicker').val();
var $today = new Date();
var $before = new Date($bef);
var $befores = $before.getFullYear();
var $todays = $today.getFullYear();
var $bmonth = $before.getMonth();
var $tmonth = $today.getMonth();
var $bday = $before.getDate();
var $tday = $today.getDate();

if ($bmonth>$tmonth)
{$('#age').val($todays-$befores);}

if ($bmonth==$tmonth)
{	
if ($tday > $bday) {$('#age').val($todays-$befores-1);}
else if ($tday <= $bday) {$('#age').val($todays-$befores);}
}
else if ($bmonth<$tmonth)
{ $('#age').val($todays-$befores-1);} 
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFranciscView Question on Stackoverflow
Solution 1 - JavascriptnaveenView Answer on Stackoverflow
Solution 2 - JavascriptAndré SnedeView Answer on Stackoverflow
Solution 3 - JavascriptKristoffer DorphView Answer on Stackoverflow
Solution 4 - JavascriptLucas JanonView Answer on Stackoverflow
Solution 5 - JavascriptVitor TyburskiView Answer on Stackoverflow
Solution 6 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 7 - JavascriptKinergyView Answer on Stackoverflow
Solution 8 - JavascriptJoshView Answer on Stackoverflow
Solution 9 - JavascriptSarwarView Answer on Stackoverflow
Solution 10 - JavascriptromulealdView Answer on Stackoverflow
Solution 11 - JavascriptMarcel KorpelView Answer on Stackoverflow
Solution 12 - JavascriptKeith NordstromView Answer on Stackoverflow
Solution 13 - JavascriptKrzysztof DąbrowskiView Answer on Stackoverflow
Solution 14 - JavascriptMartijn van HoofView Answer on Stackoverflow
Solution 15 - Javascriptcr0ybotView Answer on Stackoverflow
Solution 16 - JavascriptTWDbagView Answer on Stackoverflow
Solution 17 - JavascriptpaulinhoView Answer on Stackoverflow
Solution 18 - JavascriptAngeldevView Answer on Stackoverflow
Solution 19 - JavascriptMichael YurinView Answer on Stackoverflow
Solution 20 - Javascript20 fpsView Answer on Stackoverflow
Solution 21 - JavascriptganarajView Answer on Stackoverflow
Solution 22 - JavascriptPedro AlvaresView Answer on Stackoverflow
Solution 23 - JavascriptnazimView Answer on Stackoverflow
Solution 24 - JavascriptrsnoopyView Answer on Stackoverflow
Solution 25 - JavascriptFabricioView Answer on Stackoverflow
Solution 26 - JavascriptSSSView Answer on Stackoverflow
Solution 27 - JavascriptDBoiView Answer on Stackoverflow
Solution 28 - JavascriptIshaniNetView Answer on Stackoverflow
Solution 29 - JavascriptzubroidView Answer on Stackoverflow
Solution 30 - JavascriptConstantinView Answer on Stackoverflow
Solution 31 - JavascriptThomas FrankView Answer on Stackoverflow
Solution 32 - JavascriptMuhammad IbrahimView Answer on Stackoverflow
Solution 33 - JavascriptwizulusView Answer on Stackoverflow
Solution 34 - JavascriptxexsusView Answer on Stackoverflow
Solution 35 - JavascriptNicolas GiszpencView Answer on Stackoverflow
Solution 36 - JavascriptMikeoLeoView Answer on Stackoverflow
Solution 37 - Javascripttapos ghoshView Answer on Stackoverflow
Solution 38 - JavascriptRinat R-KView Answer on Stackoverflow
Solution 39 - JavascriptArun Prasad E SView Answer on Stackoverflow
Solution 40 - JavascriptMalik BagwalaView Answer on Stackoverflow
Solution 41 - JavascriptMark PView Answer on Stackoverflow
Solution 42 - JavascriptRobGView Answer on Stackoverflow
Solution 43 - Javascriptmohd aarifView Answer on Stackoverflow
Solution 44 - Javascriptdarkhunter761View Answer on Stackoverflow
Solution 45 - JavascriptJoselee PeñaflorView Answer on Stackoverflow