JavaScript 获取身份证年龄的完整实现与逻辑解析
作者:代码拾荒时间:2026-10-24 06:37:36浏览:560
本文详细介绍如何使用 JavaScript 根据身份证号码计算用户年龄。代码兼容15位和18位身份证格式,通过提取出生年月日并对比当前日期,自动处理闰年与月份差异,确保年龄计算的准确性。
身份证号码解析与年龄计算逻辑
/**
根据身份证号码判断性别
15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日
18位身份证号码:第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,
第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
*/
//根据身份证号获取年龄
GetAge(identityCard) {
let len = (identityCard + "").length;
let strBirthday = "";
if (len == 18) {
//处理18位的身份证号码从号码中得到生日和性别代码
strBirthday =
identityCard.substr(6, 4) +
"/" +
identityCard.substr(10, 2) +
"/" +
identityCard.substr(12, 2);
}
if (len == 15) {
let birthdayValue = "";
birthdayValue = identityCard.charAt(6) + identityCard.charAt(7);
if (parseInt(birthdayValue) < 10) {
strBirthday =
"20" +
identityCard.substr(6, 2) +
"/" +
identityCard.substr(8, 2) +
"/" +
identityCard.substr(10, 2);
} else {
strBirthday =
"19" +
identityCard.substr(6, 2) +
"/" +
identityCard.substr(8, 2) +
"/" +
identityCard.substr(10, 2);
}
}
//时间字符串里,必须是“/”
let birthDate = new Date(strBirthday);
let nowDateTime = new Date();
let age = nowDateTime.getFullYear() - birthDate.getFullYear();
//再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
if (
nowDateTime.getMonth() < birthDate.getMonth() ||
(nowDateTime.getMonth() == birthDate.getMonth() &&
nowDateTime.getDate() < birthDate.getDate())
) {
age--;
}
return age;
}
以上即为利用 JavaScript 解析身份证号码以获取年龄的完整示例。如需了解更多相关技术细节,建议查阅本站发布的其他技术文章。
作者最新文章
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
JavaScript函数定义的三种方式:声明、表达式与箭头函数
2026-11-05 13:50:55
