如何按出生日期获得年龄

时间:2011-12-17 09:21:20

标签: php

我想通过php获取var $birth_date中以下日期的确切年龄,它是怎么回事?

$birth_date = 2011/12/16;

$ birth_date =>例如,这是我的出生日期。

例如,我出生日期的输出是:0 Year, 0 Month, 1 Day

2 个答案:

答案 0 :(得分:1)

使用unix时间戳来处理生日是一个坏主意,因为它们的范围非常有限(1970-2038)。请改用php的内置DateTime类:

$then = DateTime::createFromFormat("Y/m/d", "2011/12/16");
$diff = $then->diff(new DateTime());
echo $diff->format("%y year %m month %d day\n");

答案 1 :(得分:-1)

<?php

  //calculate years of age (input string: YYYY-MM-DD)
  function birthday ($birthday, $separator){
    list($year,$month,$day) = explode($separator, $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;
  }
  echo getAge('2010/12/16', '/');
?>

http://snippets.dzone.com/posts/show/1310

重新格式化

我还推荐Tizag PHP tutorial