根据出生日期计算年龄JS代码修正,求助

JavaScript012

根据出生日期计算年龄JS代码修正,求助,第1张

写了个简单的测试,

<script>

var m=new Date()

m.setFullYear(2010,10,14)

var age=0

var d = new Date()

var year = d.getFullYear()

var month = d.getMonth() + 1

var day = d.getDate()

alert(year+"-"+month+"-"+day)

if(year>m.getFullYear()){

if(month>=m.getMonth() + 1){

if(day>=m.getDate()){

age=parseInt(year-m.getFullYear())

}else{

age=parseInt(year-m.getFullYear()-1)

}

}else{

age=parseInt(year-m.getFullYear()-1)

}

}else{

alert("0")

}

alert("age="+age)

</script>

//你也可以把以上内容写入方法,出生日期的年月日作为参数传入。注意,月份的算法

function geb(obj)

{

return document.getElementById(obj)//引入对象ID,返回某个对象

}

function tmValue(obj)

{

return geb(obj)[geb(obj).selectedIndex].value//引入select的ID,返回select的已选中的项的value值

}

function retAge()

{

var

year=tmValue('optionYear')*1,//取得选中年份的值,并转换为数字

month=tmValue('optionMonth')*1,//取得选中月份的值,并转换为数字

day=tmValue('optionDay')*1//取得选中日的值,并转换为数字

var

birthday=new data(),now=birthday//声明个生日日期变量和现在日期变量,此时两个变量都是现在的系统时间

birthday.setFullYear(year,month,day)//将年月日付给生日日期变量

var fulltime=now-birthday//得到两个日期所距离的毫秒数

//楼下说的很对,要考虑月份,所以我对我的代码作出如下调整

var age=now.getFullYear() - fulltime.getFullYear()//返回距离年

if((now.getMonth()-birthday.getMonth())>0)age+1//如果现在的月份比生日月份大,年龄变量加1

return age//返回计算后的年龄

// return fulltime /1000/60/60/24返回距离多少天

//还有你上面的input 没有 type='text'

//因为是手写的代码,所以可能存在大小写错误,自己改下

}