首页  >  文章  >  后端开发  >  PHP实现根据出生年月日计算年龄的功能(代码示例)

PHP实现根据出生年月日计算年龄的功能(代码示例)

青灯夜游
青灯夜游原创
2020-04-24 09:37:054051浏览

本篇文章给大家介绍一下使用PHP实现根据出生年月日计算年龄的功能,结合实例形式分析了php日期相关转换与计算操作技巧。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

PHP实现根据出生年月日计算年龄的功能(代码示例)

废话不多说,之间上代码:

<?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;);
?>

运行结果:

32

更多相关知识,请关注 PHP中文网!!

以上是PHP实现根据出生年月日计算年龄的功能(代码示例)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn