<script>
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(){
var age;
var aDate=new Date();
var thisYear=aDate.getFullYear();
var thisMonth=aDate.getMonth()+1;
var thisDay=aDate.getDate();
var brith=parseDate(document.getElementById("date1").value);
brithy=brith.getFullYear();
brithm=brith.getMonth();
brithd=brith.getDate();
if(thisYear-brithy<0)
{
       alert("输入错误!");
       age="";
}
else
{
       if(thisMonth-brithm<0)
       {
              age = thisYear-brithy-1;
       }
       else
       {
              if(thisDay-brithd>=0)
              {//alert(thisDay+'-'+brithd+"_ddd");
                     age = thisYear-brithy;
              }
              else
              {
                     age = thisYear-brithy-1;
              }
       }
}
document.getElementById("date2").value=age;
}
</script>
<from name="theform">
生日:<input name="date1" id="date1" onblur="getAge()">
年龄:<input name="date2" id="date2">
</form>
上面代码支持传统的日期格式:2008-06-11,2008-6-14
还有个问题:输入:2008-6-55,就没反应了~

解决方案 »

  1.   

    <script>
    function getAge(birthday){
    birthday = birthday.split("-");
    var birthday_year = birthday[0];
    var now_year = new Date().getYear() + 1900;
    var age = now_year - birthday_year + 1;
    document.getElementById("birthday").value = age;
    }
    </script>生日:<input onblur="getAge(this.value)">
    年龄:<input id="birthday">
      

  2.   

    webkit 引擎只会对 日<=31的进行自动转化,大于31则认为是错的,会对Date返回NaN。其它内核则不会。所你最好对天做判断以便兼容。
      

  3.   

    或者你换一种初始日期的方法,也没有上面的bug。比如new Date(2008,06,55)
      

  4.   

    判断一下嘛!month = (month < 10) ? ('0' + month ) : month ;
    day= (day< 10) ? ('0' + day) : day;