Sample code for getting ID age using js

  • 2021-10-13 06:22:21
  • OfStack


 /**
  Judge gender according to ID number 
 15 ID card number: number 7 , 8 The digit is the year of birth ( Double digits ) , No. 9 , 10 The position is the month of birth, the first 11 , 12 Bit represents the date of birth 
 18 ID card number: number 7 , 8 , 9 , 10 The digit is the year of birth (4 Number of digits ) , No. 11 , No. 12 The position is the month of birth, 
  No. 1 13 , 14 The number represents the date of birth, and the number 17 Bits represent gender, odd numbers are male and even numbers are female. 
 */
 // Get the age according to the ID number 
 GetAge(identityCard) {
  let len = (identityCard + "").length;
  let strBirthday = "";
  if (len == 18) {
  // Deal with 18 The ID number of digits gets the birthday and gender code from the number 
  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);
  }
  }
  // In the time string, it must be " / " 
  let birthDate = new Date(strBirthday);
  let nowDateTime = new Date();
  let age = nowDateTime.getFullYear() - birthDate.getFullYear();
  // Then consider the factors of months and days ;.getMonth() Obtained from the 0 At the beginning, we compare here, and we don't need to add 1
  if (
  nowDateTime.getMonth() < birthDate.getMonth() ||
  (nowDateTime.getMonth() == birthDate.getMonth() &&
   nowDateTime.getDate() < birthDate.getDate())
  ) {
  age--;
  }
  return age;
 }

The above is the details of the sample code for obtaining ID card age by js. Please pay attention to other related articles on this site for more information about obtaining ID card age by js!


Related articles: