计算从日期开始的年份

时间:2009-07-11 03:14:06

标签: 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');

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

4 个答案:

答案 0 :(得分:33)

您的代码无效,因为该功能未返回任何要打印的内容。

就算法而言,这是怎么回事:

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

这是与接受的答案in this question相同的算法(仅在PHP中)。

更短的做法:

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

答案 1 :(得分:11)

另一种方法是使用PHP的DateTime class,这是PHP 5.2中的新功能:

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

See it in action

答案 2 :(得分:2)

我想你需要退回$ yearDiff。

答案 3 :(得分:2)

单行功能可以在这里工作

function calculateAge($dob) {
    return floor((time() - strtotime($dob)) / 31556926);
}

计算年龄

 $age = calculateAge('1990-07-10');