js日期 转换:计算周岁

来源:互联网 发布:查看系统端口占用 编辑:程序博客网 时间:2024/04/29 16:15
<html>
<script   language=javascript>   
  function   ages(str)   
  {   
        var   r   =   str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);     
        if(r==null)return   false;     
        var   birth=   new   Date(r[1],   r[3]-1,   r[4]);     
        if   (birth.getFullYear()==r[1]&&(birth.getMonth()+1)==r[3]&&birth.getDate()==r[4])   
        {   
              var today = new Date();   
              var age = today.getFullYear()-r[1];
              
              if(today.getMonth()>birth.getMonth()){
              return age;
            }
            if(today.getMonth()==birth.getMonth()){
            if(today.getDate()>=birth.getDate()){
            return age;
            }else{
            return age-1;
            }
            }
            if(today.getMonth()<birth.getMonth()){
            return age-1;
            }
               
        }   
        return("输入的日期格式错误!");   
  }   
  alert(ages("1989-04-15"));   
  alert(ages("1989-06-13"));    
  </script>
</html>