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


当前回答

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

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

它有几个小时的剩余时间,所以根据用例,它可能不是最佳选择。

其他回答

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

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

它有几个小时的剩余时间,所以根据用例,它可能不是最佳选择。

我有一个漂亮的答案,虽然它不是我的代码。不幸的是,我忘记了原来的帖子。

function calculateAge(y, m, d) {
    var _birth = parseInt("" + y + affixZero(m) + affixZero(d));
    var  today = new Date();
    var _today = parseInt("" + today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));
    return parseInt((_today - _birth) / 10000);
}
function affixZero(int) {
    if (int < 10) int = "0" + int;
    return "" + int;
}
var age = calculateAge(1980, 4, 22);
alert(age);

试试这个:

$('#Datepicker').change(function(){

var $bef = $('#Datepicker').val();
var $today = new Date();
var $before = new Date($bef);
var $befores = $before.getFullYear();
var $todays = $today.getFullYear();
var $bmonth = $before.getMonth();
var $tmonth = $today.getMonth();
var $bday = $before.getDate();
var $tday = $today.getDate();

if ($bmonth>$tmonth)
{$('#age').val($todays-$befores);}

if ($bmonth==$tmonth)
{   
if ($tday > $bday) {$('#age').val($todays-$befores-1);}
else if ($tday <= $bday) {$('#age').val($todays-$befores);}
}
else if ($bmonth<$tmonth)
{ $('#age').val($todays-$befores-1);} 
})

从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>

function change(){
    setTimeout(function(){
        var dateObj  =      new Date();
                    var month    =      dateObj.getUTCMonth() + 1; //months from 1-12
                    var day      =      dateObj.getUTCDate();
                    var year     =      dateObj.getUTCFullYear();  
                    var newdate  =      year + "/" + month + "/" + day;
                    var entered_birthdate        =   document.getElementById('birth_dates').value;
                    var birthdate                =   new Date(entered_birthdate);
                    var birth_year               =   birthdate.getUTCFullYear();
                    var birth_month              =   birthdate.getUTCMonth() + 1;
                    var birth_date               =   birthdate.getUTCDate();
                    var age_year                =    (year-birth_year);
                    var age_month               =    (month-birth_month);
                    var age_date                =    ((day-birth_date) < 0)?(31+(day-birth_date)):(day-birth_date);
                    var test                    =    (birth_year>year)?true:((age_year===0)?((month<birth_month)?true:((month===birth_month)?(day < birth_date):false)):false) ;
                   if (test === true || (document.getElementById("birth_dates").value=== "")){
                        document.getElementById("ages").innerHTML = "";
                    }                    else{
                        var age                     =    (age_year > 1)?age_year:(   ((age_year=== 1 )&&(age_month >= 0))?age_year:((age_month < 0)?(age_month+12):((age_month > 1)?age_month:      (  ((age_month===1) && (day>birth_date) ) ? age_month:age_date)          )    )); 
                        var ages                    =    ((age===age_date)&&(age!==age_month)&&(age!==age_year))?(age_date+"days"):((((age===age_month+12)||(age===age_month)&&(age!==age_year))?(age+"months"):age_year+"years"));
                        document.getElementById("ages").innerHTML = ages;
                  }
                }, 30);

};