PHP implements the function of calculating age based on date of birth (code example)

青灯夜游
Release: 2023-04-08 14:46:02
Original
4135 people have browsed it

This article will introduce you to the function of using PHP to calculate age based on the date of birth, and analyze the PHP date-related conversion and calculation operation skills in the form of examples. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

PHP implements the function of calculating age based on date of birth (code example)

Without further ado, here’s the code:

<?php
/**
 * 根据出生年月日计算出年龄
 * @param $birth_year 
 * @param $birth_month
 * @param $birth_day
 * @return int
 */
function getAgeByBirth($birth_year,$birth_month,$birth_day){
  if(empty($birth_year) || empty($birth_month) || empty($birth_day)){
    return 0;
  }
  $current_year = date(&#39;Y&#39;,time());
  $current_month = date(&#39;m&#39;,time());
  $current_day = date(&#39;d&#39;,time());
  if($birth_year >= $current_year){
    return 0;
  }
  $age = $current_year - $birth_year - 1;
  if($current_month>$birth_month){
    return $age+1;
  }else if($current_month == $birth_month && $current_day>=$birth_day){
    return $age+1;
  }else{
    return $age;
  }
}
//测试:
echo getAgeByBirth(&#39;1988&#39;,&#39;4&#39;,&#39;8&#39;);
?>
Copy after login

Running results:

32
Copy after login

More related knowledge, Please pay attention to PHP中文网! !

The above is the detailed content of PHP implements the function of calculating age based on date of birth (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template