如果给出格式为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)) { 年龄——; } 警报(年龄);


当前回答

这是我的修改:

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

其他回答

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

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

我检查了之前展示的例子,它们并不是在所有情况下都有效,因此我自己写了一个脚本。我测试过了,效果很好。

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

我认为可以简单地像这样:

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

也适用于时间戳

age(403501000000)
//34

我会选择可读性:

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

免责声明:这也有精度问题,所以这也不能完全信任。它可以关闭几个小时,几年,或在夏令时(取决于时区)。

相反,如果精度非常重要,我建议使用一个库。还有@Naveens的帖子,可能是最准确的,因为它不依赖于一天中的时间。


我有点晚了,但我发现这是计算出生日期的最简单的方法。

希望这能有所帮助。

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>