根据身份证计算年龄


设计一个函数,入参为一个身份证号,要求返回其出生日期并计算年龄。

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 // 获取当前月份,月份从0开始
if (month < birthMonth || (month === birthMonth && today.getDate() < birthDay)) {
age-- // 如果当前月份小于出生月份,或者日期未到,则年龄减1
}

// 返回出生日期和年龄
return {
birthDate: birthDate,
age: age
}
}