PHP计算年龄

我正在寻找一种方法来计算一个人的年龄,给出他们的生日格式dd / mm / yyyy。

我正在使用以下几个月工作正常的函数,直到某种毛刺导致的while循环永远不会结束,并磨碎整个网站停下来。 由于每天几乎有数十万个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似乎工作确定一些时间,但返回“40”为14/09/1986 DOB

 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来确保date不会被误认为m/d/Y格式, DateInterval类(通过DateTime::diff )可以获得从现在开始的年数和目标date。

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

我用这个date/时间:

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

从dob计算年龄的简单方法:

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

31556926是一年中的秒数。

我觉得这个工程很简单。

从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 

//年龄计算器

 function getAge($dob,$condate){ $birthdate = new DateTime(date("Ymd", strtotime(implode('-', array_reverse(explode('/', $dob)))))); $today= new DateTime(date("Ymd", 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); 

如果你想计算使用dob的年龄,你也可以使用这个函数。 它使用DateTime对象。

 function calcutateAge($dob){ $dob = date("Ymd",strtotime($dob)); $dobObject = new DateTime($dob); $nowObject = new DateTime(); $diff = $dobObject->diff($nowObject); return $diff->y; } 

我想把这个扔在这里,因为这似乎是这个问题最stream行的forms。

我跑了100年的比较,我可以findPHP的最stream行的年龄funcs 3types,并张贴我的结果(以及function)到我的博客 。

正如你可以看到的那样,所有3个funcs都能很好地完成,而第二个函数只有轻微的差别。 根据我的结果,我的build议是使用第三个函数,除非你想在某人的生日中做一些特定的事情,在这种情况下,第一个函数提供了一个简单的方法来做到这一点。

用testing发现小问题,用第二种方法发现另一个问题! 更新即将到博客! 现在,我会注意到,第二种方法仍然是我在网上find的最stream行的,但仍然是我发现最不准确的一个!

我的100年回顾后的build议:

如果你想要更长的东西,可以包括生日等场合:

 function getAge($date) { // Ymd format $now = explode("-", date('Ym-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) { // Ymd format return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4)); } getAge('1980-02-29'); 

看BLOG


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

 Note: Dates in the m/d/y or dmy 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 dmy 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 ymd. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible. 
  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; } 

如果你不需要很高的精度,只需要几年,你可以考虑使用下面的代码…

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

你只需要把它放到一个函数中,用一个variablesreplacedate“1971-11-20”。

请注意,上面代码的精确度并不高,因为闰年​​,即大约每4年366日而不是365日。expression式60 * 60 * 24 * 365计算一年中的秒数 – 您可以将其replace为31536000。

另一个重要的是,由于使用了UNUX时间戳,它同时具有1901年和2038年的问题,这意味着上述expression式在1901年之前和2038年之后的date将无法正确工作。

如果你能忍受上述的限制,代码应该为你工作。

我发现这个脚本是可靠的。 它采用date格式为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; } 
 $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); 

i18n:

 function getAge($birthdate, $pattern = 'eu') { $patterns = array( 'eu' => 'd/m/Y', 'mysql' => 'Ym-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 

这是我计算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);  / *当地时间是2014-07-01 * /
回声sprintf(“年龄=%d年%d日月%d天”,$年龄['y'],$年龄['m'],$年龄['d']);  / *输出 - >年龄= 29岁1个月24天* /
 //replace / with - so strtotime works $dob = strtotime(str_replace("/","-",$birthdayDate)); $tdate = time(); return date('Y', $tdate) - date('Y', $dob); 

如果你似乎无法使用一些新的function,这里是我鞭打的东西。 可能比你需要的更多,我相信有更好的方法,但是很容易阅读,所以它应该做的工作:

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

希望这可以帮助。

由于闰年,从另一个date中减去一个date并将其与年数相减是不明智的。 要像人类一样计算年龄,你需要这样的东西:

 $birthday_date = '1977-04-01'; $age = date('Y') - substr($birthday_date, 0, 4); if (strtotime(date('Ym-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; } 

我已经testing并积极使用这个代码,看起来有点麻烦,但是使用和编辑起来非常简单,而且非常准确。

遵循第一个逻辑,你必须在比较中使用=。

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

与DD / MM / YYYY一起使用strtotime是个问题。 你不能使用这种格式。 而不是它,你可以使用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('dm-Y',$usersDOBtimestamp); $currentDate = date('dm-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”的date视为数字并减去它们。 之后,通过将结果除以10000并取消MMDD部分。 简单,永远不会失败,甚至考虑闰年和你当前的服务器时间;)

由于birthays或主要由出生地点的完整date提供,并且它们与当前的本地时间(实际上是在年龄检查的地方)有关。

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

所以如果你想检查一下你的时区是18岁还是21岁还是100岁以下(不要在出生时区),那么这是我的方法

这个函数将返回年龄。 input值是一个date格式(YYYY-MM-DD)出生datestring,例如: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; } 

干杯,尼拉

最简单的解决scheme是使用PHP Carbon ,它是DateTime的API扩展(请参阅http://carbon.nesbot.com/docs/#api-difference )。

只用两行就可以得到你想要的:

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

清洁和简单。

尝试这个 :

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