JS中根据出生日期计算年龄

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

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


};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值