JS根据身份证号计算出生日期、性别、年龄

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值