簡體   English   中英

PHP 計算年齡

[英]PHP calculate age

我正在尋找一種方法來計算一個人的年齡,給定他們的出生日期,格式為 dd/mm/yyyy。

我使用了下面的 function 幾個月來運行良好,直到某種故障導致 while 循環永遠不會結束並使整個站點停止運行。 由於每天有近 100,000 個 DOB 多次通過此 function,因此很難確定是什么原因造成的。

有沒有人有更可靠的計算年齡的方法?

//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));       
$tdate = time();

$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
    ++$age;
}
return $age;

編輯:這個 function 似乎在某些時候可以正常工作,但對於 1986 年 9 月 14 日的 DOB 返回“40”

return floor((time() - strtotime($birthdayDate))/31556926);

這工作正常。

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>
$tz  = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
     ->diff(new DateTime('now', $tz))
     ->y;

從 PHP 5.3.0 開始,您可以使用方便的DateTime::createFromFormat來確保您的日期不會被誤認為是m/d/Y格式和DateInterval類(通過DateTime::diff )來獲得現在之間的年數和目標日期。

 $date = new DateTime($bithdayDate);
 $now = new DateTime();
 $interval = $now->diff($date);
 return $interval->y;

我為此使用日期/時間:

$age = date_diff(date_create($bdate), date_create('now'))->y;

從dob計算年齡的簡單方法:

$_age = floor((time() - strtotime('1986-09-16')) / 31556926);

31556926是一年中的秒數。

// 年齡計算器

function getAge($dob,$condate){ 
    $birthdate = new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $dob))))));
    $today= new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $condate))))));           
    $age = $birthdate->diff($today)->y;

    return $age;
}

$dob='06/06/1996'; //date of Birth
$condate='07/02/16'; //Certain fix Date of Age 
echo getAge($dob,$condate);

我發現這很有效而且很簡單。

從 1970 中減去,因為 strtotime 從 1970-01-01 開始計算時間( http://php.net/manual/en/function.strtotime.php

function getAge($date) {
    return intval(date('Y', time() - strtotime($date))) - 1970;
}

結果:

Current Time: 2015-10-22 10:04:23

getAge('2005-10-22') // => 10
getAge('1997-10-22 10:06:52') // one 1s before  => 17
getAge('1997-10-22 10:06:50') // one 1s after => 18
getAge('1985-02-04') // => 30
getAge('1920-02-29') // => 95

您可以使用Carbon,它是 DateTime 的 API 擴展。

你可以:

function calculate_age($date) {
    $date = new \Carbon\Carbon($date);
    return (int) $date->diffInYears();
}

或:

$age = (new \Carbon\Carbon($date))->age;

我想我會把這個扔在這里,因為這似乎是這個問題最受歡迎的形式。

我對我能找到的 3 種最流行的 PHP 年齡函數進行了 100 年的比較,並將我的結果(以及函數)發布到了我的博客

正如您在那里看到的,所有 3 個 funcs 都很好地執行,只是在第二個函數上略有不同。 基於我的結果,我的建議是使用第三個函數,除非您想在某人的生日做一些特定的事情,在這種情況下,第一個函數提供了一種簡單的方法來做到這一點。

發現測試的小問題,以及第二種方法的另一個問題! 即將更新到博客! 現在,我要注意,第二種方法仍然是我在網上找到的最受歡迎的方法,但仍然是我發現最不准確的方法!

我的 100 年回顧后的建議:

如果你想要更細長的東西,這樣你就可以包括生日之類的場合:

function getAge($date) { // Y-m-d format
    $now = explode("-", date('Y-m-d'));
    $dob = explode("-", $date);
    $dif = $now[0] - $dob[0];
    if ($dob[1] > $now[1]) { // birthday month has not hit this year
        $dif -= 1;
    }
    elseif ($dob[1] == $now[1]) { // birthday month is this month, check day
        if ($dob[2] > $now[2]) {
            $dif -= 1;
        }
        elseif ($dob[2] == $now[2]) { // Happy Birthday!
            $dif = $dif." Happy Birthday!";
        };
    };
    return $dif;
}

getAge('1980-02-29');

如果你只是想知道年齡而已,那么:

function getAge($date) { // Y-m-d format
    return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}

getAge('1980-02-29');

見博客


關於strtotime方法的關鍵說明:

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the 
separator between the various components: if the separator is a slash (/), 
then the American m/d/y is assumed; whereas if the separator is a dash (-) 
or a dot (.), then the European d-m-y format is assumed. If, however, the 
year is given in a two digit format and the separator is a dash (-, the date 
string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or 
DateTime::createFromFormat() when possible.

如果你想計算使用dob的年齡,也可以使用這個函數。 它使用 DateTime 對象。

function calcutateAge($dob){

        $dob = date("Y-m-d",strtotime($dob));

        $dobObject = new DateTime($dob);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);

        return $diff->y;

}

編寫一個 PHP 腳本來計算一個人的當前年齡。

樣本出生日期:11.4.1987

示例解決方案:

PHP代碼:

<?php
$bday = new DateTime('11.4.1987'); // Your date of birth
$today = new Datetime(date('m.d.y'));
$diff = $today->diff($bday);
printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
printf("\n");
?>

示例輸出:

您的年齡 : 30 歲 3 個月零 0 天

$birthday_timestamp = strtotime('1988-12-10');  

// Calculates age correctly
// Just need birthday in timestamp
$age = date('md', $birthday_timestamp) > date('md') ? date('Y') - date('Y', $birthday_timestamp) - 1 : date('Y') - date('Y', $birthday_timestamp);

如果你不需要很高的精度,只需要年數,你可以考慮使用下面的代碼......

 print floor((time() - strtotime("1971-11-20")) / (60*60*24*365));

你只需要把它放到一個函數中,並用一個變量替換日期“1971-11-20”。

請注意,由於閏年,上面代碼的精度不高,即大約每 4 年天數是 366 而不是 365。表達式 60*60*24*365 計算一年中的秒數 - 你可以將其替換為 31536000。

另一個重要的事情是,由於使用UNIX時間戳,它同時存在 1901 年和 2038 年問題,這意味着上面的表達式對於 1901 年之前和 2038 年之后的日期將無法正常工作。

如果您可以忍受上面提到的限制,那么代碼應該適合您。

國際化:

function getAge($birthdate, $pattern = 'eu')
{
    $patterns = array(
        'eu'    => 'd/m/Y',
        'mysql' => 'Y-m-d',
        'us'    => 'm/d/Y',
    );

    $now      = new DateTime();
    $in       = DateTime::createFromFormat($patterns[$pattern], $birthdate);
    $interval = $now->diff($in);
    return $interval->y;
}

// Usage
echo getAge('05/29/1984', 'us');
// return 28

使用 DateTime 對象嘗試其中任何一個

$hours_in_day   = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;

$birth_date     = new DateTime("1988-07-31T00:00:00");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";
echo $hours     = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins      = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds   = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";

參考http://www.calculator.net/age-calculator.html

//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));       
$tdate = time();
return date('Y', $tdate) - date('Y', $dob);
  function dob ($birthday){
    list($day,$month,$year) = explode("/",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0)
      $year_diff--;
    return $year_diff;
  }

我發現這個腳本可靠。 它采用日期格式為 YYYY-mm-dd,但可以很容易地修改為其他格式。

/*
* Get age from dob
* @param        dob      string       The dob to validate in mysql format (yyyy-mm-dd)
* @return            integer      The age in years as of the current date
*/
function getAge($dob) {
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ($day_diff < 0 || $month_diff < 0)
        $year_diff--;

    return $year_diff;
}

這是我用按年、月和日具體返回的年齡來計算 DOB 的函數

function ageDOB($y=2014,$m=12,$d=31){ /* $y = year, $m = month, $d = day */
date_default_timezone_set("Asia/Jakarta"); /* can change with others time zone */

$ageY = date("Y")-intval($y);
$ageM = date("n")-intval($m);
$ageD = date("j")-intval($d);

if ($ageD < 0){
    $ageD = $ageD += date("t");
    $ageM--;
    }
if ($ageM < 0){
    $ageM+=12;
    $ageY--;
    }
if ($ageY < 0){ $ageD = $ageM = $ageY = -1; }
return array( 'y'=>$ageY, 'm'=>$ageM, 'd'=>$ageD );
}

這是如何使用它

$age = ageDOB(1984,5,8); /* with my local time is 2014-07-01 */
echo sprintf("age = %d years %d months %d days",$age['y'],$age['m'],$age['d']); /* output -> age = 29 year 1 month 24 day */

此函數將返回以年為單位的年齡。 輸入值是日期格式 (YYYY-MM-DD) 出生日期字符串,例如:2000-01-01

它適用於白天 - 精度

function getAge($dob) {
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    // if we are any month before the birthdate: year - 1 
    // OR if we are in the month of birth but on a day 
    // before the actual birth day: year - 1
    if ( ($month_diff < 0 ) || ($month_diff === 0 && $day_diff < 0))
        $year_diff--;   

    return $year_diff;
}

干杯,尼拉

如果您似乎無法使用某些較新的功能,這是我提出的一些建議。 可能比你需要的更多,我相信有更好的方法,但它很容易閱讀,所以它應該可以完成這項工作:

function get_age($date, $units='years')
{
    $modifier = date('n') - date('n', strtotime($date)) ? 1 : (date('j') - date('j', strtotime($date)) ? 1 : 0);
    $seconds = (time()-strtotime($date));
    $years = (date('Y')-date('Y', strtotime($date))-$modifier);
    switch($units)
    {
        case 'seconds':
            return $seconds;
        case 'minutes':
            return round($seconds/60);
        case 'hours':
            return round($seconds/60/60);
        case 'days':
            return round($seconds/60/60/24);
        case 'months':
            return ($years*12+date('n'));
        case 'decades':
            return ($years/10);
        case 'centuries':
            return ($years/100);
        case 'years':
        default:
            return $years;
    }
}

使用示例:

echo 'I am '.get_age('September 19th, 1984', 'days').' days old';

希望這會有所幫助。

由於閏年,從另一個日期中減去一個日期並將其歸入年數是不明智的。 要像人類一樣計算年齡,你需要這樣的東西:

$birthday_date = '1977-04-01';
$age = date('Y') - substr($birthday_date, 0, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($birthday_date, 4, 6)) < 0)
{
    $age--;
}

以下對我來說非常有用,並且似乎比已經給出的示例簡單得多。

$dob_date = "01";
$dob_month = "01";
$dob_year = "1970";
$year = gmdate("Y");
$month = gmdate("m");
$day = gmdate("d");
$age = $year-$dob_year; // $age calculates the user's age determined by only the year
if($month < $dob_month) { // this checks if the current month is before the user's month of birth
  $age = $age-1;
} else if($month == $dob_month && $day >= $dob_date) { // this checks if the current month is the same as the user's month of birth and then checks if it is the user's birthday or if it is after it
  $age = $age;
} else if($month == $dob_month && $day < $dob_date) { //this checks if the current month is the user's month of birth and checks if it before the user's birthday
  $age = $age-1;
} else {
  $age = $age;
}

我已經測試並積極使用此代碼,它可能看起來有點麻煩但使用和編輯非常簡單並且非常准確。

按照第一個邏輯,您必須在比較中使用 =。

<?php 
    function age($birthdate) {
        $birthdate = strtotime($birthdate);
        $now = time();
        $age = 0;
        while ($now >= ($birthdate = strtotime("+1 YEAR", $birthdate))) {
            $age++;
        }
        return $age;
    }

    // Usage:

    echo age(implode("-",array_reverse(explode("/",'14/09/1986')))); // format yyyy-mm-dd is safe!
    echo age("-10 YEARS") // without = in the comparison, will returns 9.

?>

當您將 strtotime 與 DD/MM/YYYY 一起使用時,這是一個問題。 你不能使用那種格式。 您可以使用 MM/DD/YYYY(或許多其他格式,如 YYYYMMDD 或 YYYY-MM-DD)代替它,它應該可以正常工作。

如何啟動此查詢並讓 MySQL 為您計算它:

SELECT 
username
,date_of_birth
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) DIV 12 AS years
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) MOD 12 AS months
FROM users

結果:

r2d2, 1986-12-23 00:00:00, 27 , 6 

用戶有 27 年零 6 個月(算一整月)

我是這樣做的。

$geboortedatum = 1980-01-30 00:00:00;
echo leeftijd($geboortedatum) 

function leeftijd($geboortedatum) {
    $leeftijd = date('Y')-date('Y', strtotime($geboortedatum));
    if (date('m')<date('m', strtotime($geboortedatum)))
        $leeftijd = $leeftijd-1;
    elseif (date('m')==date('m', strtotime($geboortedatum)))
       if (date('d')<date('d', strtotime($geboortedatum)))
           $leeftijd = $leeftijd-1;
    return $leeftijd;
}

對此的最佳答案是可以,但只計算一個人出生的年份,我出於自己的目的對其進行了調整以計算出日期和月份。 但認為值得分享。

這是通過獲取用戶 DOB 的時間戳來工作的,但可以隨意更改

$birthDate = date('d-m-Y',$usersDOBtimestamp);
$currentDate = date('d-m-Y', time());
//explode the date to get month, day and year
$birthDate = explode("-", $birthDate);
$currentDate = explode("-", $currentDate);
$birthDate[0] = ltrim($birthDate[0],'0');
$currentDate[0] = ltrim($currentDate[0],'0');
//that gets a rough age
$age = $currentDate[2] - $birthDate[2];
//check if month has passed
if($birthDate[1] > $currentDate[1]){
      //user birthday has not passed
      $age = $age - 1;
} else if($birthDate[1] == $currentDate[1]){ 
      //check if birthday is in current month
      if($birthDate[0] > $currentDate[0]){
            $age - 1;
      }


}
   echo $age;

如果你只想得到整年的年齡,有一個超級簡單的方法來做到這一點。 將格式為 'YYYYMMDD' 的日期視為數字並減去它們。 之后,通過將結果除以 10000 來抵消 MMDD 部分並將其降低。 簡單且永不失敗,甚至考慮閏年和您當前的服務器時間;)

由於生日或主要由出生地點的完整日期提供,並且它們與當前本地時間(實際完成年齡檢查的地方)相關。

$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birthday)/10000);

因此,如果您想在生日之前檢查某人在您的時區(不要介意原始時區)上是否為 18 歲或 21 歲或低於 100 歲,這就是我的方法

這是更簡單的過程,適用於 dd/mm/yyyy 和 dd-mm-yyyy 格式。 這對我很有用:

    <?php
        
       $birthday = '26/04/1994';
                                                            
       $dob = strtotime(str_replace("/", "-", $birthday));
       $tdate = time();
       echo date('Y', $tdate) - date('Y', $dob);

   ?>

試試這個:

<?php
  $birth_date = strtotime("1988-03-22");
  $now = time();
  $age = $now-$birth_date;
  $a = $age/60/60/24/365.25;
  echo floor($a);
?>

我使用以下方法來計算年齡:

$oDateNow = new DateTime();
$oDateBirth = new DateTime($sDateBirth);

// New interval
$oDateIntervall = $oDateNow->diff($oDateBirth);

// Output
echo $oDateIntervall->y;

這是計算年齡的簡單函數:

<?php
    function age($birthDate){
      //date in mm/dd/yyyy format; or it can be in other formats as well
      //explode the date to get month, day and year
      $birthDate = explode("/", $birthDate);
      //get age from date or birthdate
      $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
        ? ((date("Y") - $birthDate[2]) - 1)
        : (date("Y") - $birthDate[2]));
     return $age;
    }

    ?>

    <?php
    echo age('11/05/1991');
    ?>

准備使用返回完整結果(年、月、日、小時、分鍾、秒)的函數。 關於當前日期之上的日期,它將返回對倒計時功能有用的負值

/* By default,
* format is 'us'
* and delimiter is '-'
*/

function date_calculate($input_date, $format = 'us', $delimiter = '-')
{
    switch (strtolower($format)) {
        case 'us': // date in 'us' format (yyyy/mm/dd), like '1994/03/01'
            list($y, $m, $d) = explode($delimiter, $input_date);
            break;
        case 'fr': // date in 'fr' format (dd/mm/yyyy), like '01/03/1994'
            list($d, $m, $y) = explode($delimiter, $input_date);
            break;
        default: return null;
    }

    $tz          = new \DateTimeZone('UTC'); // TimeZone. Not required but can be useful. By default, server TimeZone will be returned
    $format_date = sprintf('%s-%s-%s', $y, $m, $d);
    $cur_date    = new \DateTime(null, $tz);
    $user_date   = new \DateTime($format_date, $tz);
    $interval    = $user_date->diff($cur_date);

    return [
        'year'  => $interval->format('%r%y'),
        'month' => $interval->format('%r%m'),
        'day'   => $interval->format('%r%d'),
        'hour'  => $interval->format('%r%H'),
        'min'   => $interval->format('%r%i'),
        'sec'   => $interval->format('%r%s'),
    ];
}

var_dump(date_calculate('06/09/2016', 'fr', '/'));
var_dump(date_calculate('2016-09-06'));

更多++:

縱觀提供的解決方案,我一直在思考現代教育在 IT 領域的弊端。 大多數開發人員都忘記了即使是現代 CPU 也會執行條件運算符,而算術運算,尤其是 2 的冪運算更快。 因此,我在沒有任何優化的情況下在 PHP 線程中展示了這個解決方案:

  list($year,$month,$day) = explode("-",$birthday);
  $age=floor(((date("Y")-$year)*512+(date("m")-$month)*32+date("d")-$day)/512);

在其他具有嚴格類型定義並能夠通過移位替換 * 和 / 的語言中,此公式將“飛”。 還可以更改除數,您可以按月、周等計算年齡。 小心,差異中操作數的順序是必不可少的

此功能工作正常。 這是對 Parkyprg 代碼的輕微改進

function age($birthday){
 list($day,$month,$year) = explode("/",$birthday);
 $year_diff  = date("Y") - $year;
 $month_diff = date("m") - $month;
 $day_diff   = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0){$year_diff--;}
 if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
 return $year_diff;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM