JS根据身份证获取出生日期、性别、年龄等方法 您所在的位置:网站首页 根据身份证号码提取出生日期 JS根据身份证获取出生日期、性别、年龄等方法

JS根据身份证获取出生日期、性别、年龄等方法

2024-04-14 17:20| 来源: 网络整理| 查看: 265

前言

早期‘身份证号码’叫‘社会保障号’,为15位,1999年开始更名为公民身份证号码,即第二代身份证,为18位,且终身不变。本文方法均以18位身份证号为例。

获取出生日期 /** * @param no 接收的字符串(身份证号) * @param slipt 分割方式,默认:- * @param isDate 是否只显示月日,默认:false * @param isRreverse 是否为倒叙显示,如:日-月-年,默认:false * @returns string 脱敏后的字符串 */ const getBirth = (no = '', slipt = '-', isDate = false, isRreverse = false) => { if (!no) return no const toStr = no.toString() const yearStr = toStr.substring(6, 10) const dateStr = `${toStr.substring(10, 12)}${slipt}${toStr.substring(12, 14)}` const reulst = isDate ? dateStr : `${yearStr}${slipt}${dateStr}` return isRreverse ? reulst.split(slipt).reverse().join(slipt) : reulst }

需求一:身份证号:12010120210622207X;显示为:2021-06-22

getBirth('12010120210622207X')

测试结果: image.png

需求二:身份证号:12010120210622207X;显示为:2021/06/22

getBirth('12010120210622207X','/')

测试结果: image.png

需求三:身份证号:12010120210622207X;显示为:06-22

getBirth('12010120210622207X','-',true)

测试结果: image.png

需求四:身份证号:12010120210622207X;显示倒叙:22/06/2021

getBirth('12010120210622207X','/','',true)

测试结果: image.png

获取性别方法 const getSex = (no = '') => { if (!no) return no const toStr = no.toString() if (toStr.length < 17) return no return Number(toStr.substring(16, 17)) % 2 ? '男' : '女' }

使用方式:

getSex('12010120210622207X')

测试结果: image.png

获取年龄

调用此方法的时候,需要依赖于获取出生日期方法;

const getAge = (no = '') => { if (!no) return no const toStr = no.toString() const birth = new Date(getBirth(toStr)) const today = new Date() let age = today.getFullYear() - birth.getFullYear() if ( today.getMonth() < birth.getMonth() || (today.getMonth() == birth.getMonth() && today.getDate() < birth.getDate()) ) { age-- } return age }

使用方式:

getAge('12010120210622207X')

测试结果: image.png

判断是否符合年龄 /** * @param no 接收的字符串(身份证号) * @param targetAge 目标年龄,默认:18 * @returns boolean 是否满足年龄 */ const isMeetAge = (no = '', targetAge = 18) => { if (!no) return no return getAge(no)


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有