以PHP计算出生日期的年龄


Calculating age from date of birth in PHP

您遇到的最精确的函数是什么,可以从用户的出生日期计算年龄。我有以下代码,想知道如何改进它,因为它不支持所有日期格式,也不确定它是否是最准确的函数(符合日期时间会很好)。

function getAge($birthday) {
    return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
echo $interval->y;

应该工作

检查这个

<?php
$c= date('Y');
$y= date('Y',strtotime('1988-12-29'));
echo $c-$y;
?>

使用此代码具有完整的年龄,包括年,月和日-

    <?php
     //full age calulator
     $bday = new DateTime('02.08.1991');//dd.mm.yyyy
     $today = new DateTime('00:00:00'); // Current date
     $diff = $today->diff($bday);
     printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
    ?>

尝试为此使用 DateTime:

$now      = new DateTime();
$birthday = new DateTime('1973-04-18 09:48:00');
echo $now->diff($birthday)->format('%y years'); // 49 years

查看实际效果

这有效:

<?
$date = date_create('1984-10-26');
$interval = $date->diff(new DateTime);
echo $interval->y;
?>

如果你告诉我你的$birthday变量是什么格式的,我会给你确切的解决方案

WTF?

strtotime(date('d-m-Y'))

因此,您从当前时间戳生成日期字符串,然后将日期字符串转换回时间戳?

顺便说一句,它不起作用的原因之一是 strtotime() 假设数字日期采用 m/d/y 格式(即日期优先的美国格式)。另一个原因是公式中未使用参数 ($birthday)。

$date更改为 $birthday

为了晚饭的准确性,您需要考虑闰年因素:

function get_age($dob_day,$dob_month,$dob_year){
    $year   = gmdate('Y');
    $month  = gmdate('m');
    $day    = gmdate('d');
     //seconds in a day = 86400
    $days_in_between = (mktime(0,0,0,$month,$day,$year) - mktime(0,0,0,$dob_month,$dob_day,$dob_year))/86400;
    $age_float = $days_in_between / 365.242199; // Account for leap year
    $age = (int)($age_float); // Remove decimal places without rounding up once number is + .5
    return $age;
}

所以使用:

echo get_date(31,01,1985);

什么的...

:注:查看您的确切年龄到小数点

return $age_float

相反。

这个函数工作正常。

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

查看博客文章

这是我

的长/详细版本(如果需要,可以缩短):

$timestamp_birthdate = mktime(9, 0, 0, $birthdate_month, $birthdate_day, $birthdate_year);
$timestamp_now = time();
$difference_seconds = $timestamp_now-$timestamp_birthdate;
$difference_minutes = $difference_seconds/60;
$difference_hours = $difference_minutes/60;
$difference_days = $difference_hours/24;
$difference_years = $difference_days/365;