Javascript - 计算年龄

时间:2014-12-05 12:08:53

标签: javascript date

我试图计算用户的日期但不计算正确的方式

这是我的代码

var cpr = cprValue.toString();

// cpr is = 0102907896

var dd = cpr.substr(0, 2); // 01
var mm = cpr.substr(2, 2); // 02
var yy = cpr.substr(4, 2); // 90

// Calculate if 90 is > 50
if (yy > 50) {
  var year = 1900;
} else {
  var year = 2000;
}


var curDate  = new Date();
var curYear  = curDate.getUTCFullYear(),
curMonth = curDate.getUTCMonth(),
curDay   = curDate.getUTCDate();


var myAge = curYear % year;

if (curMonth < mm && curDay < dd || curMonth < mm && curDay === dd || curMonth == mm && `curDay < dd) {`
  myAge  -= 1;
}

console.log(myAge);

我的输出是13,但它应该是24

BUT

如果我改变dd,mm,yy并像这样硬编码

var dd = 01;
var mm = 02;
var year = 1990;

然后它工作,输出是24年。 我在这做错了什么?

修改

我试过这个,但如果我的年份是1990年,我仍然会得到114,但是如果我把这个日期定为罚款:S

var cpr = cprValue.toString();

//cpr is = 0102907896

var dd = cpr.substr(0, 2); // 01
var mm = cpr.substr(2, 2); // 02
var yy = cpr.substr(4, 2); // 90

//Calculate if 90 is > 50
if (yy>50) {
  var year = 1900;
} else {
  var year = 2000;
}

var final = year + "-" + mm + "-" + dd;
console.log("Final: "+ final);

var alder = moment().diff(final, 'years');
console.log(alder);

2 个答案:

答案 0 :(得分:0)

这是一种方式:

function getAge(d1, d2){
    d2 = d2 || new Date();
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log( getAge(new Date(1978, 10, 3)) );

此处存在解决方案:javascript - Age calculation

另一种解决方案:

function calculateAge (birthDate, otherDate) {
    birthDate = new Date(birthDate);
    otherDate = new Date(otherDate);

    var years = (otherDate.getFullYear() - birthDate.getFullYear());

    if (otherDate.getMonth() < birthDate.getMonth() || 
        otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}

示例:

var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY

答案 1 :(得分:0)

或者你可以:

&#13;
&#13;
var result = document.querySelector('#results');

result.innerHTML += 'birthDate 2002/11/11, age today: '+ 
                    age(new Date('2002/11/11'));
result.innerHTML += '<br>birthDate 1944/12/15, age today: '+ 
                    age(new Date('1944/12/11'));
result.innerHTML += '<br>birthDate 1954/12/04, age today: '+ 
                    age(new Date('1954/12/04'));
result.innerHTML += '<br>birthDate 1954/12/06 age on 2013/12/03: '+ 
                    age(new Date('1954/12/06'), new Date('2013/12/03'));


function age(birthDate, forDate) {
   forDate = forDate || new Date;
   
   return (forDate.getFullYear() - birthDate.getFullYear())
          +
          (forDate.getMonth() < birthDate.getMonth() || forDate.getMonth() == birthDate.getMonth() && forDate.getDate() < birthDate.getDate() ? -1 : 0);
}
&#13;
<div id="results"></div>
&#13;
&#13;
&#13;