calculateAgeFromIdCard(idCardNumber) {
const birthYear = parseInt(idCardNumber.substr(6, 4))
const birthMonth = parseInt(idCardNumber.substr(10, 2))
const birthDay = parseInt(idCardNumber.substr(12, 2))
const now = new Date()
const currentYear = now.getFullYear()
const currentMonth = now.getMonth() + 1
const currentDay = now.getDate()
let age = currentYear - birthYear
let monthDiff = 0
let dayDiff = 0
if (
currentMonth < birthMonth ||
(currentMonth === birthMonth && currentDay < birthDay)
) {
age--
monthDiff = 12 - birthMonth + currentMonth
} else {
monthDiff = currentMonth - birthMonth
}
if (monthDiff < 0) {
age--
monthDiff += 12
}
dayDiff = currentDay - birthDay
if (dayDiff < 0) {
monthDiff--
const lastDayOfMonth = new Date(
currentYear,
currentMonth - 1 - (monthDiff > 0 ? 1 : 0),
0
).getDate()
dayDiff = lastDayOfMonth + dayDiff
}
if (age > 0) {
return age + '岁'
} else if (monthDiff > 0) {
return monthDiff + '个月'
} else {
return dayDiff + '天'
}
},
const idCardNumber = "你的身份证号码";
console.log(calculateAgeFromIdCard(idCardNumber));