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


当前回答

下面是我能想到的最简单、最准确的解决方案:

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

下面是一个考虑每年2月29日至2月28日的例子。

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

它甚至适用于负年龄!

其他回答

重要提示:这个答案并不能提供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));

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

我相信在这种情况下,有时可读性更重要。除非我们要验证1000个字段,否则这应该足够准确和快速:

函数is18orOlder(dateString) { const dob = new Date(dateString); const dobPlus18 =新的日期(dob.getFullYear() + 18, dob.getMonth(), dob.getDate()); 返回dobPlus18 .valueOf() <= Date.now(); } / /测试: console.log (is18orOlder (' 01/01/1910 '));/ /正确的 console.log (is18orOlder (' 01/01/2050 '));/ /错误 //当我在2020年10月2日发布这篇文章时,所以: console.log (is18orOlder (' 10/08/2002 '));/ /正确的 console.log(is18orOlder('10/19/2002')) // false

我喜欢这种方法,而不是用一个常数来表示一年有多少毫秒,然后再弄乱闰年等等。让内置的Date来做这个工作。

更新,发布这个片段,因为有人可能会发现它有用。因为我在输入字段上强制一个掩码,有mm/dd/yyyy的格式,并且已经验证了日期是否有效,在我的情况下,这也适用于验证18+年:

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

还有另一个解决方案:

/**
 * 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;
}
$("#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);

    }
}
});

从naveen和原始OP的帖子中采用,我最终得到了一个可重用的方法存根,它接受字符串和/或JS Date对象。

我将其命名为gregorianAge(),因为这个计算准确地给出了我们如何使用公历表示年龄。即,如果月和日在出生年份的月和日之前,则不计算结束年。

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