如果给出格式为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 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 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';
}

这对我来说是最优雅的方式:

const getAge = (birthDateString) => { const today = new Date(); const birthDate = new Date(birthDateString); const yearsDifference = today.getFullYear() - birthDate.getFullYear(); 如果( 今天。getmonth () < birthDate.getMonth() || . getmonth ( (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())) ) { 返回yearsDifference - 1; } 返回yearsDifference; }; console.log (getAge (' 2018-03-12 '));

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

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

从日期选择器计算年龄

         $('#ContentPlaceHolder1_dob').on('changeDate', function (ev) {
            $(this).datepicker('hide');

            //alert($(this).val());
            var date = formatDate($(this).val()); // ('2010/01/18') to ("1990/4/16"))
            var age = getAge(date);

            $("#ContentPlaceHolder1_age").val(age);
        });


    function formatDate(input) {
        var datePart = input.match(/\d+/g),
        year = datePart[0], // get only two digits
        month = datePart[1], day = datePart[2];
        return day + '/' + month + '/' + year;
    }

    // alert(formatDate('2010/01/18'));


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

我知道这是一个非常古老的线程,但我想把这个实现放在我写的寻找年龄,我相信这是更准确的。

var getAge = function(year,month,date){
    var today = new Date();
    var dob = new Date();
    dob.setFullYear(year);
    dob.setMonth(month-1);
    dob.setDate(date);
    var timeDiff = today.valueOf() - dob.valueOf();
    var milliInDay = 24*60*60*1000;
    var noOfDays = timeDiff / milliInDay;
    var daysInYear = 365.242;
    return  ( noOfDays / daysInYear ) ;
}

当然,你可以调整它以适应其他获取参数的格式。希望这有助于人们寻找更好的解决方案。