计算从日期开始的年份

14 php datetime

我正在寻找一个函数,从格式:0000-00-00的日期计算年数.发现这个功能,但它不会工作.

// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
  // Explode the date into meaningful variables
  list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
  // Find the differences
  $YearDiff = date("Y") - $BirthYear;
  $MonthDiff = date("m") - $BirthMonth;
  $DayDiff = date("d") - $BirthDay;
  // If the birthday has not occured this year
  if ($DayDiff < 0 || $MonthDiff < 0)
  $YearDiff--;
 }

echo getAge('1990-04-04');
Run Code Online (Sandbox Code Playgroud)

什么都不输出:/
我有错误报告,但我没有得到任何错误

Pao*_*ino 34

您的代码不起作用,因为该函数未返回任何要打印的内容.

算法去了,怎么样:

function getAge($then) {
    $then_ts = strtotime($then);
    $then_year = date('Y', $then_ts);
    $age = date('Y') - $then_year;
    if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
    return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
Run Code Online (Sandbox Code Playgroud)

这是与此问题中接受的答案相同的算法(仅在PHP中).

更简单的方法:

function getAge($then) {
    $then = date('Ymd', strtotime($then));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*nde 12

另一种方法是使用PHP的DateTime类,它是PHP 5.2中的新:

$birthdate = new DateTime("1986-06-18");
$today     = new DateTime();
$interval  = $today->diff($birthdate);
echo $interval->format('%y years');
Run Code Online (Sandbox Code Playgroud)

看到它在行动


Abh*_*waj 5

单行函数可以在这里工作

function calculateAge($dob) {
    return floor((time() - strtotime($dob)) / 31556926);
}
Run Code Online (Sandbox Code Playgroud)

计算年龄

 $age = calculateAge('1990-07-10');
Run Code Online (Sandbox Code Playgroud)