您的位置:首页 > Web前端 > JavaScript

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

2012-12-25 14:18 741 查看
我们经常会碰到需要根据出生日期计算年龄的需求,这里给出一个例子:

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

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: