js函数实现根据出生日期求年龄

来源:互联网 发布:sqlserver 大数据 编辑:程序博客网 时间:2024/05/29 14:42

我们经常会碰到需要根据出生日期计算年龄的需求,这里给出一个例子:

function parseDate(str){
if(str.match(/^\d{4}[\-\/\s+]\d{1,2}[\-\/\s+]\d{1,2}$/)){
return new Date(str.replace(/[\-\/\s+]/i,'/'));
}else if(str.match(/^\d{8}$/)){
return new Date(str.substring(0,4)+'/'+str.substring(4,6)+'/'+str.substring(6));
}else{
alert('date parse error');
}
};

function getAge(cell){
var age;
//alert(cell);
var aDate=new Date();
var thisYear=aDate.getFullYear();
var thisMonth=aDate.getMonth()+1;
var thisDay=aDate.getDate();
var birth=parseDate(document.getElementById("report1_"+cell).value);
//alert(birth);
var birthy=birth.getFullYear();
var birthm=birth.getMonth()+1;
var birthd=birth.getDate();
if(thisYear-birthy<0)
{
       alert("输入错误!");
       age="";
}
else
{
       if(thisMonth-birthm<0)
       {
              age = thisYear-birthy-1;
       }
       else
       {
              if(thisDay-birthd>=0)
              {
                     age = thisYear-birthy;
              }
              else
              {
                     age = thisYear-birthy-1;
              }
       }
}


return(age);


};

原创粉丝点击