PHP to achieve accurate age based on ID card

Time:2021-6-6

preface

Sometimes, we want to calculate the age through the ID card, so the function I write below is very suitable.

realization

There are detailed comments in the code.

function getAge($id){

#1. Get the date of birth from the ID card
$id = $id;// ID
$birth_ Date = strtotime(substr($id, 6, 8));// Intercept date and convert to timestamp

#2. Format [date of birth]
$Year = date('Y', $birth_Date);//yyyy
$Month = date('m', $birth_Date);//mm
$Day = date('d', $birth_Date);//dd

#3. Format [current date]
$current_Y = date('Y');//yyyy
$current_M = date('m');//mm
$current_D = date('d');//dd

#4. Calculate age ()
$age = $current_ Y - $Year;// This year minus birthday year
if($Month > $current_ M || $Month == $current_ M && $Day > $current_ D) {// deep judgment (Japan)
 $age--;// If the month of birth is greater than or equal to the current month but the birthday is greater than or equal to the current day, one year will be deducted
}
#Back
return $age;

}

use

By calling the getAge () method, the ID number can be counted.

#Argument must be of type string
echo getAge('130322xxxxxxxxxx14');
// xx

Let’s share another piece of code: ID card to get age information:

/*
* age based on ID number.
* inupt $code = complete ID number.
*Return $age: age
*/
function ageVerification($code){
 $age_time = strtotime(substr($code, 6, 8));
 if($age_time === false){
 return false;
 }
 list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age_time)); 
 
 $now_time = strtotime("now");
 
 list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now_time));
 $age = $y2 - $y1;
 if((int)($m2.$d2) < (int)($m1.$d1)){
 $age -= 1;
 }
 return $age; 
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]