JS根据身份证号码精确计算年龄和性别

 1 /**
 2  * 根据身份证号得到姓别和精确计算年龄
 3  */
 4 function analyzeIDCard(IDCard){
 5     var sexAndAge = {};
 6     //获取用户身份证号码
 7     var userCard = IDCard;
 8     //如果身份证号码为undefind则返回空
 9     if(!userCard){
10         return sexAndAge;
11     }
12     //获取性别
13     if(parseInt(userCard.substr(16,1)) % 2 == 1){
14         sexAndAge.sex = '1(男)'
15     }else{
16         sexAndAge.sex = '0(女)'
17     }
18     //获取出生年月日
19     //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
20     var yearBirth = userCard.substring(6,10);
21     var monthBirth = userCard.substring(10,12);
22     var dayBirth = userCard.substring(12,14);
23     //获取当前年月日并计算年龄
24     var myDate = new Date();
25     var monthNow = myDate.getMonth() + 1;
26     var dayNow = myDate.getDay();
27     var age = myDate.getFullYear() - yearBirth;
28     if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
29         age--;
30     }
31     //得到年龄
32     sexAndAge.age = age;
33     //返回性别和年龄
34     return sexAndAge;
35 }
36 
37 /*测试*/
38 var ID = analyzeIDCard('510612199004174732');
39 console.info(ID);

 

posted @ 2018-05-03 11:18  哈喽叮  阅读(1640)  评论(0编辑  收藏  举报