//通过身份证号计算年龄、性别、出生日期,userCard:身份证号的字符串,不能是数字 function idCard(userCard) { // 身份证正则表达式 var re = /^\d{6}(((19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}([0-9]|x|X))|(\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}))$/; if (!re.test(userCard)) { // 测试身份证是否正确 console.log("身份证号码格式有误,请重新填写!"); return false; } else { console.log('身份证正确') } var obj = { sex:'', age:'', } //获取出生日期 obj.birth = userCard.substring(6, 10) + "-" + userCard.substring(10, 12) + "-" + userCard.substring(12, 14); //获取性别 if (parseInt(userCard.substr(16, 1)) % 2 == 1) { obj.sex = "男"; } else { obj.sex = "女"; } //获取年龄 var myDate = new Date(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); var age = myDate.getFullYear() - userCard.substring(6, 10) - 1; if (userCard.substring(10, 12) < month || userCard.substring(10, 12) == month && userCard.substring(12, 14) <= day) { age++; } obj.age = age return obj; }
标签:10,12,myDate,身份证号,userCard,substring,var,js,性别 From: https://www.cnblogs.com/haqiao/p/18397778