Javascript 以 YYYYMMDD 格式计算给定出生日期的年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4060004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:19:21  来源:igfitidea点击:

Calculate age given the birth date in the format YYYYMMDD

javascriptdate

提问by Francisc

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date()function?

给定格式 YYYYMMDD 的出生日期,如何计算以年为单位的年龄?是否可以使用该Date()功能?

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

采纳答案by André Snede Kock

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.

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



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

基准:http: //jsperf.com/birthday-calculation/15

回答by naveen

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

我相信您的代码中唯一看起来粗糙的就是substr零件。

Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/

小提琴http: //jsfiddle.net/codeandcloud/n33RJ/

回答by Kristoffer Dorph

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

重要提示:此答案不能提供 100% 准确的答案,根据日期的不同,它会延迟大约 10-20 小时。

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

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

The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:

答案看起来像这样,运行速度比 naveen 快 65%,而且它更短:

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.

神奇的数字:31557600000 是 24 * 3600 * 365.25 * 1000 这是一年的长度,一年的长度是 365 天和 6 小时是 0.25 天。最后,我给出了最终年龄的结果。

Here is the benchmarks: http://jsperf.com/birthday-calculation

这是基准: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));

要支持 OP 的数据格式,您可以替换+new Date(dateString);
+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! :-)

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

回答by Vitor Tyburski

With momentjs:

使用momentjs:

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

回答by Lucas Janon

Clean one-liner solution using ES6:

使用 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.

我使用的年份为 365.25 天(由于闰年为 0.25),分别为 3.15576e+10 毫秒(365.25 * 24 * 60 * 60 * 1000)。

回答by CMS

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:

它需要一个 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

回答by Kinergy

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
}

回答by Josh

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

回答by Marcel Korpel

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,它有效地返回了一年中的天数。其余的都是不言自明的。

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

回答by Sarwar

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