javascript根据身份证号判断精确周岁年龄

前言:

根据身份证号判断精确周岁年龄,可以精确到天,即周岁以生日当天为准,生日当天周岁+1,少一天则不加。

实现方法:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8 <script>
 9     
10 /**
11  * 根据身份证号,获取精缺周岁年龄
12  * @param {Object} strBirthday    生日格式:19880808
13  */
14 function getAgeByPid(strBirthday){          
15     var birthYear = strBirthday.substr(0,4)
16     var birthMonth = strBirthday.substr(4,2)
17     var birthDay = strBirthday.substr(6,2)
18       
19     d = new Date();  
20     var nowYear = d.getFullYear();  
21     var nowMonth = d.getMonth() + 1;  
22     var nowDay = d.getDate();  
23       
24     if(nowYear == birthYear)  
25     {  
26         returnAge = 0;//同年 则为0岁  
27     }  
28     else  
29     {  
30         var ageDiff = nowYear - birthYear ; //年之差  
31         if(ageDiff > 0)  
32         {  
33             if(nowMonth == birthMonth)  
34             {  
35                 var dayDiff = nowDay - birthDay;//日之差  
36                 if(dayDiff < 0)  
37                 {  
38                     returnAge = ageDiff - 1;  
39                 }  
40                 else  
41                 {  
42                     returnAge = ageDiff ;  
43                 }  
44             }  
45             else  
46             {  
47                 var monthDiff = nowMonth - birthMonth;//月之差  
48                 if(monthDiff < 0)  
49                 {  
50                     returnAge = ageDiff - 1;  
51                 }  
52                 else  
53                 {  
54                     returnAge = ageDiff ;  
55                 }  
56             }  
57         }  
58         else  
59         {  
60             returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天  
61         }  
62     }  
63     return returnAge;//返回周岁年龄   
64 }  
65 /**
66  * 获取年龄的单击事件
67  */
68 function getAge(){
69     var pid=document.getElementById("txtPid").value;
70     pid=pid.substr(6,8)
71     alert(getAgeByPid(pid))
72 }
73 </script>
74 <input type="text" name="pid" id="txtPid">
75 <input type="button" value="查询" id="btnGetAge" onclick="getAge()">
76 </body>
77 </html>

 

posted on 2017-04-24 19:53  逍遥云天  阅读(1579)  评论(0编辑  收藏  举报

导航