PHP 计算年龄

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 计算年龄相关的知识,希望对你有一定的参考价值。

/**
 * Calculate age in years based on timestamp and reference timestamp
 * If the reference $now is set to 0, then current time is used
 *
 * @param int $timestamp
 * @param int $now
 * @return int
 */
function calculateAge($timestamp = 0, $now = 0) {
    # default to current time when $now not given
    if ($now == 0)
        $now = time();

    # calculate differences between timestamp and current Y/m/d
    $yearDiff   = date("Y", $now) - date("Y", $timestamp);
    $monthDiff  = date("m", $now) - date("m", $timestamp);
    $dayDiff    = date("d", $now) - date("d", $timestamp);

    # check if we already had our birthday
    if ($monthDiff < 0)
        $yearDiff--;
    elseif (($monthDiff == 0) && ($dayDiff < 0))
        $yearDiff--;

    # set the result: age in years
    $result = intval($yearDiff);

    # deliver the result
    return $result;
}

以上是关于PHP 计算年龄的主要内容,如果未能解决你的问题,请参考以下文章

PHP 用PHP计算年龄;给定的出生日期

PHP 从DOB计算年龄

PHP 计算年龄

PHP 计算年龄

PHP 计算年龄

PHP 计算年龄