php 实现根据证件获取精准年龄

  有时候,我们希望通过证件来计算出年龄,那么下面我写的函数很适合。

  实现

  代码中已有详细注释。

  function getAge($id){

  # 1.从证件中获取出生日期

  $id = $id;//证件

  $birth_Date = strtotime(substr($id, 6, 8));//截取日期MT4自动交易自动交易并转为时间戳

  # 2.格式化[出生日期]

  $Year = date('Y', $birth_Date);//yyyy

  $Month = date('m', $birth_Date);//mm

  $Day = date('d', $birth_Date);//dd

  # 3.格式化[当前日期]

  $current_Y = date('Y');//yyyy

  $current_M = date('m');//mm

  $current_D = date('d');//dd

  # 4.计算年龄()

  $age = $current_Y - $Year;//今年减去生日年

  if($Month > $current_M || $Month == $current_M && $Day > $current_D){//深层判断(日)

  $age--;//如果出生月大于当前月或出生月等于当前月但出生日大于当前日则减一岁

  }

  # 返回

  return $age;

  }

  使用

  通过调用 getAge() 方法,传入证件号即可计算。

  # 参数必须为 String 型

  echo getAge('130322xxxxxxxxxx14');

  // xx

猜你喜欢

转载自blog.51cto.com/14511863/2473580