JS根据身份证号计算出生日期、性别、年龄
一、根据身份证号计算出生日期、性别、年龄
util.js
import Vue from 'vue'
const getInfoByIdCardFun = function (idCard) {
// 15位/18位身份证号
let regExp = /(^[1-9]\d{7}(?:0\d|10|11|12)(?:0[1-9]|[1-2][\d]|30|31)\d{3}$)|(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)/
let birthday, sex, age
if (regExp.test(idCard)) {
if (idCard.length === 15) {
// 获取出生日期
let Y = idCard.substr(6, 1) == 0 ? '20' : '19';
birthday = Y + [idCard.substr(6, 2), idCard.substr(8, 2), idCard.substr(10, 2)].join('-')
// 获取性别
sex = ['女', '男'][idCard.substr(14, 1) % 2]
}
else {
// 获取出生日期
birthday = [idCard.substr(6, 4), idCard.substr(10, 2), idCard.substr(12, 2)].join('-')
// 获取性别
sex = ['女', '男'][idCard.substr(16, 1) % 2]
}
// 获取年龄
age = getAgeByBirthday(birthday)
} else {
birthday = ''
sex = ''
age = ''
}
let idCardInfo = {
birthday: birthday,
sex: sex,
age: age,
}
console.log(idCardInfo)
return idCardInfo
}
Vue.prototype.$getInfoByIdCardFun = getInfoByIdCardFun
// 根据生日获取年龄
function getAgeByBirthday(val) {
let currentYear = new Date().getFullYear() //当前的年份
let calculationYear = new Date(val).getFullYear() //计算的年份
const wholeTime = currentYear + val.substring(4) //周岁时间
const calculationAge = currentYear - calculationYear //按照年份计算的年龄
//判断是否过了生日
if (new Date().getTime() > new Date(wholeTime).getTime()) {
return calculationAge
} else {
return calculationAge - 1
}
}
二、使用
main.js
import '@/components/common/js/util.js'
this.birthday = this.$getInfoByIdCardFun(idCard).birthday
this.sex = this.$getInfoByIdCardFun(idCard).sex
this.age = this.$getInfoByIdCardFun(idCard).age