PHP计算年龄

PHP计算年龄,php,Php,我正在寻找一种方法来计算一个人的年龄,给定他们的DOB格式为dd/mm/yyyy 我一直在使用下面的函数,这个函数在几个月内运行良好,直到出现某种小故障,导致while循环永远不会结束,并使整个站点停止运行。由于每天有将近100000个DOB通过此功能数次,因此很难确定是什么导致了这一现象 有人有更可靠的计算年龄的方法吗 //replace / with - so strtotime works $dob = strtotime(str_replace("/","-",$birthdayDate

我正在寻找一种方法来计算一个人的年龄,给定他们的DOB格式为dd/mm/yyyy

我一直在使用下面的函数,这个函数在几个月内运行良好,直到出现某种小故障,导致while循环永远不会结束,并使整个站点停止运行。由于每天有将近100000个DOB通过此功能数次,因此很难确定是什么导致了这一现象

有人有更可靠的计算年龄的方法吗

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

$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
    ++$age;
}
return $age;
编辑:此函数在某些时候似乎工作正常,但对于1986年9月14日的DOB返回“40”

return floor((time() - strtotime($birthdayDate))/31556926);
函数dob($birth){
列表($day、$month、$year)=爆炸(“/”,$birth);
$year_diff=日期(“Y”)-$year;
$month_diff=日期(“m”)-$month;
$day_diff=日期(“d”)-$day;
如果($day_diff<0 |$$month_diff<0)
$year_diff--;
返回$year_diff;
}
从PHP5.3.0开始,您可以使用方便的
DateTime::createFromFormat
来确保您的日期不会被误认为
m/d/Y
格式和
DateInterval
类(通过
DateTime::diff
)来获取从现在到目标日期之间的年数。

这很好

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


如果你不需要很大的精度,只是几年的时间,你可以考虑使用下面的代码……/P>

 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年之后的日期将无法正常工作


如果您能够接受上述限制,那么代码应该适合您。

我发现这个脚本是可靠的。它的日期格式为YYYY-mm-dd,但可以很容易地修改为其他格式

$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);
/*
* 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获得年龄
*@param dob string以mysql格式验证的dob(yyyy-mm-dd)
*@return integer截止当前日期的年龄(以年为单位)
*/
函数getAge($dob){
//计算年龄(输入字符串:YYYY-MM-DD)
列表($year,$month,$day)=爆炸(“-”,$dob);
$year_diff=日期(“Y”)-$year;
$month_diff=日期(“m”)-$month;
$day_diff=日期(“d”)-$day;
如果($day_diff<0 |$$month_diff<0)
$year_diff--;
返回$year_diff;
}

我想我会把这个放在这里,因为这似乎是这个问题最流行的形式

我对PHP中最流行的3种年龄函数进行了100年的比较,并将结果(以及函数)发布到

正如您所看到的,所有3个函数都能很好地执行,第2个函数只有一点不同。根据我的结果,我的建议是使用第三个函数,除非你想在一个人的生日做一些特定的事情,在这种情况下,第1个函数提供了一种简单的方法

在测试中发现小问题,在第二种方法中发现另一个问题!更新即将来到博客!现在,我要注意,第二种方法仍然是我在网上找到的最流行的方法,但仍然是我发现最不准确的方法

我的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');


关于该方法的一个关键注意事项:


如果要计算使用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;

}

如果你似乎不能使用一些较新的函数,下面是我突然想到的。可能比你需要的要多,我相信有更好的方法,但它很容易阅读,所以应该可以:

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--;
}
$birth_date='1977-04-01';
$age=date('Y')-substr($birth_date,0,4);
if(strotime(date('Y-m-d'))-strotime(date('Y')).substr('birth_date,4,6))<0)
{
$age--;
}

根据出生日期计算年龄的简单方法:

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

31556926
是一年中的秒数。

以下内容对我来说非常有用,似乎比前面给出的示例简单得多

$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;
}
$dob_date=“01”;
$dob_month=“01”;
$dob_year=“1970”;
$year=gmdate(“Y”);
$month=gmdate(“m”);
$day=gmdate(“d”);
$age=$year-$dob_year;//$年龄计算仅由年份确定的用户年龄
if($month<$dob_month){//检查当前月份是否在用户出生月份之前
$age=$age-1;
}else if($month==$dob_month&&$day>=$dob_date){//检查当前月份是否与用户的出生月份相同,然后检查是用户的生日还是在该月份之后
$age=$age;
}else if($month==$dob_month&&$day<$dob_date){//检查当前月份是否为用户的出生月份,并检查是否在用户的生日之前
$age=$age-1;
}否则{
$age=$age;
}
我已经测试并积极使用了这段代码,它可能看起来有点麻烦,但使用和编辑起来非常简单,而且非常准确。

i18n:

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

按照第一个逻辑,在比较中必须使用=

<?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.

?>

将strotime与DD/MM/YYYY一起使用时会出现问题。你不能用那种格式。您可以使用MM/DD/yyyyy(或许多其他类似于YYYYMMDD或yyyyy-MM-DD)来代替它,它应该可以正常工作。

我使用日期/时间来表示
$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--;
}
$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
$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;
}
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
<?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.

?>
$age = date_diff(date_create($bdate), date_create('now'))->y;
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 
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 */
$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;
}
<?php
  $birth_date = strtotime("1988-03-22");
  $now = time();
  $age = $now-$birth_date;
  $a = $age/60/60/24/365.25;
  echo floor($a);
?>
$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;
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
$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birthday)/10000);
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;
}
$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/>";
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);
function calculate_age($date) {
    $date = new \Carbon\Carbon($date);
    return (int) $date->diffInYears();
}
$age = (new \Carbon\Carbon($date))->age;
<?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");
?>