设计一个函数,入参为一个身份证号,要求返回其出生日期并计算年龄。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function getIdCardInfo(id) { if (!/^\d{18}$/.test(id)) { console.log('身份证格式不正确') return }
const birthDateStr = id.substring(6, 14) const birthYear = parseInt(birthDateStr.substring(0, 4), 10) const birthMonth = parseInt(birthDateStr.substring(4, 6), 10) const birthDay = parseInt(birthDateStr.substring(6, 8), 10)
const birthDate = new Date(birthYear, birthMonth - 1, birthDay)
const today = new Date() let age = today.getFullYear() - birthYear const month = today.getMonth() + 1 if (month < birthMonth || (month === birthMonth && today.getDate() < birthDay)) { age-- }
return { birthDate: birthDate, age: age } }
|