在JavaScript中计算/检查出生日期不到110年

时间:2014-11-25 14:08:34

标签: javascript sql arrays validation date

我有这样的日期数组:

var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];

我想做的是检查/计算每个出生日期元素,看看年龄是否小于110岁,仅基于年份。如果年龄大于110岁(也仅基于年份),那么我希望从dateArray中删除/删除此元素。

基本上,我要做的是在JavaScript中转换以下SQL代码:

FROM TABLE X
WHERE TO_CHAR(DOB, 'YYYY') > (TO_CHAR(TO_DATE('2014/09/30', 'YYYY/MM/DD'), 'YYYY') - 110)

非常感谢。

2 个答案:

答案 0 :(得分:0)

使用the .getFullYear() method of Date type

for(var i=0;i<dateArray.length;i++)
{
   var now = new Date();// or specify any date you want with new Date("2014/10/15");
   var birth = new Date(dateArray[i]);
   var age = now.getFullYear() - birth.getFullYear();
   //then use the age var and test if it's bigger than 110
}

应该这样做。

答案 1 :(得分:0)

我将如何做到这一点:

var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];
dateArray = removeOldPeople(dateArray);

function removeOldPeople(dateArray){ 
    //looping backwards because I delete items from array in loop
    for(var i = dateArray.length -1 ; i >=0 ; i--){
      var dateString = dateArray[i].split("-");
      var year = dateString[0];
      var month = parseInt(dateString[1])-1;
      var day = dateString[2];
      var age = calculateAge(day, month, year);
        if(age >= 110) {
            dateArray =  dateArray.splice(i);
        }
    }
}

function calculateAge(birthMonth, birthDay, birthYear){
  todayDate = new Date();
  todayYear = todayDate.getFullYear();
  todayMonth = todayDate.getMonth();
  todayDay = todayDate.getDate();
  age = todayYear - birthYear; 

  if (todayMonth < birthMonth - 1){
    age--;
  }

  if (birthMonth - 1 == todayMonth && todayDay < birthDay){
    age--;
  }
  return age;
}