根据身份证号码获取生日、年龄、性别
- 判断是否是身份证号码
- 获取生日日期
- 通过生日计算年龄
- 性别判断
// 判断身份证号是否合法
function isCard (str){
var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return reg.test(str);
}
// 通过身份证号获取生日日期
function GetBirthday (identityCard){
var len = (identityCard + “”).length;
var strBirthday = "";
if (!isCard (identityCard)){
return false;
}
if (len == 0){
return false;
} else {
// 身份证号码只能为15位或18位其它不合法
if ((len != 15) && (len != 18)){
return false;
}
}
// 处理18位的身份证号码从号码中得到生日和性别代码
if (len == 18){
strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
}
if (len == 15) {
strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
}
// 时间字符串里,必须是“/”
return new Date(strBirthday);
}
// 根据身份证号获取年龄
function GetAge(identityCard){
var nowDateTime = new Date();
var age = 0;
var birthDate = GetBirthday(identityCard);
if (birthDate){
age = nowDateTime.getFullYear() - birthDate.getFullYear();
// 再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
age--;
}
}else{
return age;
}
}
// 根据身份证号码获取性别
function GetSex(card){
// 获取性别
if (parseInt(card.substr(16, 1)) % 2 == 1) {
return 0;//男
} else {
return 1;//女
}
}