要根据身份证号码获取年龄,可以使用JavaScript编写一个函数来实现。以下是一个完整的示例代码,包含基础概念解释和相关步骤:
/**
* 根据身份证号码获取年龄
* @param {string} idCard - 18位身份证号码
* @returns {number|null} 年龄,如果身份证格式不正确则返回null
*/
function getAgeByIdCard(idCard) {
// 身份证号码的正则表达式,验证格式
const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
if (!reg.test(idCard)) {
console.error('身份证号码格式不正确');
return null;
}
// 提取出生日期
let birthDateStr;
if (idCard.length === 15) {
// 15位身份证转换为18位
birthDateStr = '19' + idCard.substring(6, 12);
} else {
birthDateStr = idCard.substring(6, 14);
}
const year = parseInt(birthDateStr.substring(0, 4), 10);
const month = parseInt(birthDateStr.substring(4, 6), 10) - 1; // 月份从0开始
const day = parseInt(birthDateStr.substring(6, 8), 10);
const birthDate = new Date(year, month, day);
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const currentMonth = today.getMonth();
const birthMonth = birthDate.getMonth();
// 如果当前月份小于出生月份,或者月份相同但日期未到,则年龄减一
if (
currentMonth < birthMonth ||
(currentMonth === birthMonth && today.getDate() < birthDate.getDate())
) {
age--;
}
return age;
}
// 示例使用
const idCard = '11010519491231002X'; // 示例身份证号码
const age = getAgeByIdCard(idCard);
if (age !== null) {
console.log(`年龄为:${age}岁`);
}
YYYYMMDD
。YYMMDD
。X
(大小写均可)。Date
对象处理日期计算。通过上述方法,可以准确地根据身份证号码计算出对应的年龄。如有进一步的问题或需要更复杂的校验,可以在此基础上进行扩展。
领取专属 10元无门槛券
手把手带您无忧上云