通过身份证计算出出生日期、年龄和性别
有时候我们需要通过身份证来计算这个人的出生日期、性别和年龄,下面的方法就可以实现这个需求。
const analyzeIdCard = idCard => {
console.log(typeof idCard);
console.log(idCard);
let birthday = idCard.substring(6, 14);
let gender = parseInt(idCard.charAt(16)) % 2 === 0 ? "女" : "男";
let birthYear = parseInt(birthday.substring(0, 4));
let birthMonth = parseInt(birthday.substring(4, 6));
let birthDay = parseInt(birthday.substring(6, 8));
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth() + 1; // 月份从 0 开始,需要加 1
let currentDay = new Date().getDate();
let age = currentYear - birthYear;
// 如果当前月份小于出生月份,或者当前月份等于出生月份但当前日期小于出生日期,则年龄减一
if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
age--;
}
// 创建包含birthday ,age 和 gender 的对象
let analysisResult = {
birthday: birthday ,
age: age,
gender: gender
};
return analysisResult; // 返回包含birthday ,age 和 gender的对象
};
--------------------------------------------------------------------
下面是关于该方法的使用:
let result = analyzeIdCard('身份证号')
console.log(result.age,'年龄');
console.log(result.gender,'性别');
console.log(result.birthday,'生日');