溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用JavaScript怎么根據(jù)身份證獲取年齡

發(fā)布時間:2020-12-14 14:58:29 來源:億速云 閱讀:269 作者:Leah 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)利用JavaScript怎么根據(jù)身份證獲取年齡,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

 /**
 根據(jù)身份證號碼判斷性別
 15位身份證號碼:第7、8位為出生年份(兩位數(shù)),第9、10位為出生月份,第11、12位代表出生日
 18位身份證號碼:第7、8、9、10位為出生年份(四位數(shù)),第11、第12位為出生月份,
 第13、14位代表出生日期,第17位代表性別,奇數(shù)為男,偶數(shù)為女。
 */
 //根據(jù)身份證號獲取年齡
 GetAge(identityCard) {
  let len = (identityCard + "").length;
  let strBirthday = "";
  if (len == 18) {
  //處理18位的身份證號碼從號碼中得到生日和性別代碼
  strBirthday =
   identityCard.substr(6, 4) +
   "/" +
   identityCard.substr(10, 2) +
   "/" +
   identityCard.substr(12, 2);
  }
  if (len == 15) {
  let birthdayValue = "";
  birthdayValue = identityCard.charAt(6) + identityCard.charAt(7);
  if (parseInt(birthdayValue) < 10) {
   strBirthday =
   "20" +
   identityCard.substr(6, 2) +
   "/" +
   identityCard.substr(8, 2) +
   "/" +
   identityCard.substr(10, 2);
  } else {
   strBirthday =
   "19" +
   identityCard.substr(6, 2) +
   "/" +
   identityCard.substr(8, 2) +
   "/" +
   identityCard.substr(10, 2);
  }
  }
  //時間字符串里,必須是“/”
  let birthDate = new Date(strBirthday);
  let nowDateTime = new Date();
  let age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考慮月、天的因素;.getMonth()獲取的是從0開始的,這里進(jìn)行比較,不需要加1
  if (
  nowDateTime.getMonth() < birthDate.getMonth() ||
  (nowDateTime.getMonth() == birthDate.getMonth() &&
   nowDateTime.getDate() < birthDate.getDate())
  ) {
  age--;
  }
  return age;
 }

上述就是小編為大家分享的利用JavaScript怎么根據(jù)身份證獲取年齡了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI