如果给出格式为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 dobvalidator(birthDateString){
    strs = birthDateString.split("-");
    var dd = strs[0];
    var mm = strs[1];
    var yy = strs[2];

    var d = new Date();
    var ds = d.getDate();
    var ms = d.getMonth();
    var ys = d.getFullYear();
    var accepted_age = 18;

    var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
    var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);

    if((days - age) <= '0'){
        console.log((days - age));
        alert('You are at-least ' + accepted_age);
    }else{
        console.log((days - age));
        alert('You are not at-least ' + accepted_age);
    }
}

其他回答

不久前,我做了一个这样的函数:

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

它接受一个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

我相信在这种情况下,有时可读性更重要。除非我们要验证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();
}

这个问题已经超过10年了,没有人回答过提示,他们已经有了YYYYMMDD格式的出生日期?

如果你有一个YYYYMMDD格式的过去日期和当前日期,你可以像这样快速计算它们之间的年数:

var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)

你可以得到当前日期格式为YYYYMMDD,如下所示:

var now = new Date();

var currentDate = [
    now.getFullYear(),
    ('0' + (now.getMonth() + 1) ).slice(-2),
    ('0' + now.getDate() ).slice(-2),
].join('');

还有两个选择:

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

试试这个:

$('#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);} 
})