js根据身份证获取年龄,性别,出生日期
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>js根据身份证获取年龄,性别,出生日期</title>
</head>
<body>
</body>
<script type="text/javascript">
var card = '350781196403070948';
/*
params:{
idNo:"",//证件号
type:1 获取性别 2 年龄 3 身份证
}
*/
function getIdnoObj(idNo, type) {
if (idNo.length != 18) return "证件号长度不合法";
//截取 6 到10 位 获取到出生年龄
let str1 = idNo.substring(6, 10);
let str2 = idNo.substring(10, 12);
let str3 = idNo.substring(12, 14);
//获取性别
if (type == 1) {
//获取出生年月
let num = idNo.charAt(16);
if (num % 2 == 0) {
return `女`;
} else {
return `男`;
}
} else if (type == 2) {
return `${str1}-${str2}-${str3}`;
//获取年龄
} else if (type == 3) {
//获取当前年份
let myDate = new Date();
let month = myDate.getMonth() + 1;
let day = myDate.getDate();
let age = myDate.getFullYear() - str1 - 1;
//判断生日过了没有
if (str2 < month || str2 == month && str3 <= day) {
age++;
}
return age;
}
}
//调用方式
console.log(getIdnoObj(card, 3))
</script>
</html>