首頁  >  文章  >  後端開發  >  PHP實作根據出生年月日計算年齡的功能(程式碼範例)

PHP實作根據出生年月日計算年齡的功能(程式碼範例)

青灯夜游
青灯夜游原創
2020-04-24 09:37:054031瀏覽

這篇文章為大家介紹一下使用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