js通过身份证获取年龄

it2025-02-03  15

// 获取用户的身份证号码 let identityCard = this.idNum.replace(/\s+/g, ""); //判断长度 let len = identityCard.length; //设置新的变量 var strBirthday = ""; //根据长度获取年月日 if (len == 18) { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //格式化用户的年月日信息 let birthDate = new Date(strBirthday); //创建新的年月日信息 let nowDateTime = new Date(); //新的年份 - 用户年份 var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //通过月份最终获取用户年龄 if ( nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate()) ) { age--; } //查看年龄 console.log(age);
最新回复(0)