【问题标题】:Calculate years from date从日期开始计算年份
【发布时间】:2010-11-09 21:57:46
【问题描述】:

我正在寻找一个从日期开始计算年份的函数,格式为: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');

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

【问题讨论】:

  • 这个函数没有return 行,因此它不输出任何东西。看起来很不完整。

标签: php datetime


【解决方案1】:

我认为你需要返回 $yearDiff。

【讨论】:

    【解决方案2】:

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

    就算法而言,这个怎么样:

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

    【讨论】:

    • 在第二种方式中,您不应该修改输入 $then。您应该将其存储为单独的变量。
    【解决方案3】:

    另一种方法是使用 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

    【讨论】:

    • 小修正:DateTime::diff() 自 PHP 5.3 起是新的
    【解决方案4】:

    单行函数可以在这里工作

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

    计算年龄

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

    【讨论】:

      猜你喜欢
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      相关资源
      最近更新 更多