如果给出格式为YYYYMMDD的出生日期,如何以年计算年龄?是否可以使用Date()函数?

我正在寻找一个比我现在使用的更好的解决方案:

Var dob = '19800810'; var年=数字(dob.)substr (0, 4)); var月=数字(dob.)Substr (4, 2)) - 1; var day =数字(dob.)2) substr(6日); var today = new Date(); var age = today.getFullYear() -年份; if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) { 年龄——; } 警报(年龄);


当前回答

重要提示:这个答案并不能提供100%的准确答案,根据日期的不同,它会有10-20个小时的误差。

没有更好的解决方案(至少在这些答案中没有)。——纳文

我当然无法抗拒接受挑战的冲动,制作一个比目前公认的解决方案更快、更短的生日计算器。 我的解决方案的要点是,数学是快速的,所以不是使用分支和javascript提供的日期模型来计算解决方案,我们使用美妙的数学

答案是这样的,运行速度比naveen快65%,而且更短:

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

神奇的数字:31557600000等于24 * 3600 * 365.25 * 1000 也就是一年的长度,一年的长度是365天6小时,也就是0.25天。最后,我对结果进行了统计,得出了最终的年龄。

以下是基准测试:http://jsperf.com/birthday-calculation

要支持OP的数据格式,可以替换+new Date(dateString); +新日期(d。Substr (0,4), d.substr(4,2)-1, d.substr(6,2));

如果你能想出一个更好的解决方案,请分享!:-)

其他回答

还有另一个解决方案:

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

获取欧洲日期输入时的年龄:

getAge('16-03-1989')

不久前,我做了一个这样的函数:

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

它接受一个Date对象作为输入,所以你需要解析'YYYYMMDD'格式的日期字符串:

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

如果年龄只是为了显示(可能不是100%准确),下面的答案是一个很好的方法,但至少它更容易让你理解

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

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