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);
};
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);
};
相关文章推荐
- js实现根据出生日期计算年龄
- js 根据出生日期获得年龄
- JS实现根据出生年月计算年龄
- JS:根据出生日期 得到年龄
- js 正则表达式根据出生日期获得年龄
- JS中根据出生日期计算年龄
- js实现根据身份证号自动生成出生日期
- php根据出生日期计算年龄函数
- JS实现根据出生年月计算年龄
- JS根据身份证号提取出生日期并计算年龄
- sql server 根据身份证号计算出生日期和年龄的存储过程
- [置顶] 【go语言计算年龄生肖星座】go语言根据出生日期 计算年龄,所属星座,生肖
- JS 验证身份证号 根据身份证号获取出生日期
- php根据出生日期计算年龄
- 根据出生日期算出年龄
- 在Excel中根据某一个单元格的出生日期自动精确计算年龄
- sql根据出生日期计算年龄
- 根据身份证号,使用Java编写程序获取年龄、性别、出生日期
- JS日期:根据出生日期 得到周岁年龄
- 用JS实现自动提取身份证的出生日期