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


当前回答

还有两个选择:

// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
    try {
        var d = new Date();
        var new_d = '';
        d.setFullYear(d.getFullYear() - Math.abs(age));
        new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();

        return new_d;
    } catch(err) {
        console.log(err.message);
    }
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
    try {
        var today = new Date();
        var d = new Date(date);

        var year = today.getFullYear() - d.getFullYear();
        var month = today.getMonth() - d.getMonth();
        var day = today.getDate() - d.getDate();
        var carry = 0;

        if (year < 0)
            return 0;
        if (month <= 0 && day <= 0)
            carry -= 1;

        var age = parseInt(year);
        age += carry;

        return Math.abs(age);
    } catch(err) {
        console.log(err.message);
    }
}

其他回答

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

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

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

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

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

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

这是我的解决方案,只需要传入一个可解析的日期:

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
}

我只是不得不为自己写这个函数-接受的答案是相当好的,但IMO可以使用一些清理。这需要一个unix时间戳的dob,因为这是我的要求,但可以迅速适应使用字符串:

var getAge = function(dob) {
    var measureDays = function(dateObj) {
            return 31*dateObj.getMonth()+dateObj.getDate();
        },
        d = new Date(dob*1000),
        now = new Date();

    return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}

注意,我在measureDays函数中使用了31的固定值。所有计算所关心的是“年中的一天”是时间戳的单调递增度量。

如果使用javascript时间戳或字符串,显然需要删除1000的因子。