Calculate age given the birth date in the format Y

2018-12-31 02:24发布

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

30条回答
步步皆殇っ
2楼-- · 2018-12-31 03:05

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
查看更多
何处买醉
3楼-- · 2018-12-31 03:05
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';
}
查看更多
泪湿衣
4楼-- · 2018-12-31 03:06

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!

查看更多
素衣白纱
5楼-- · 2018-12-31 03:07

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

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 03:09

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
查看更多
一个人的天荒地老
7楼-- · 2018-12-31 03:09

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>

查看更多
登录 后发表回答