PHP计算人的当前年龄

时间:2010-08-01 06:20:51

标签: php date

我的网站上的出生日期格式为12.01.1980

$person_date (string) = Day.Month.Year

想要添加一个人的故乡。比如“目前30年”(2010年 - 1980年= 30年​​)。

但仅仅几年的功能不能给出完美的结果:

如果出生日期为12.12.1980且当前日期为01.01.2010,则该人的年龄为30岁。这是29年零一个月。

必须计算出与当前日期比较出生年份,月份和日期的计算:

0)解析日期。

Birth date (Day.Month.Year):
Day = $birth_day;
Month = $birth_month;
Year = $birth_year;

Current date (Day.Month.Year):
Day = $current_day;
Month = $current_month;
Year = $current_year;

1)年份比较,2010年 - 1980年=写“30”(让它为$total_year变量)

2)比较月份,如果(出生日期月份大于>当前月份(如出生时12岁和01当前)){从$total_year变量减去一年(30 - 1 = 29) }。如果发生减号,则在此时完成计算。否则进入下一步(3步)。

3)else if (birth month < current month) { $total_year = $total_year (30); }

4)else if (birth month = current month) { $total_year = $total_year (30); }

并检查当天(在此步骤中):

 if(birth day = current day) { $total_year = $total_year; }
 else if (birth day > current day) { $total_year = $total_year -1; }
 else if (birth day < current day) { $total_year = $total_year; }

5)echo $ total_year;

我的PHP知识不好,希望你能帮忙。

感谢。

3 个答案:

答案 0 :(得分:38)

您可以使用DateTime class及其diff()方法。

<?php
$bday = new DateTime('12.12.1980');
// $today = new DateTime('00:00:00'); - use this for the current date
$today = new DateTime('2010-08-01 00:00:00'); // for testing purposes

$diff = $today->diff($bday);

printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);

打印29 years, 7 month, 20 days

答案 1 :(得分:6)

@ VolkerK答案的延伸 - 非常棒!我从不喜欢看零年龄,如果你只使用年份就会发生这种情况。此功能显示他们的月龄(如果他们是一个月或更长),以及其他几天。

function calculate_age($birthday)
{
    $today = new DateTime();
    $diff = $today->diff(new DateTime($birthday));

    if ($diff->y)
    {
        return $diff->y . ' years';
    }
    elseif ($diff->m)
    {
        return $diff->m . ' months';
    }
    else
    {
        return $diff->d . ' days';
    }
}

答案 2 :(得分:2)

我进一步扩展了@ Jonathan的回答,以提供更“人性化”的回应。

使用这些日期:

$birthday= new DateTime('2011-11-21');
//Your date of birth.

并调用此函数:

function calculate_age($birthday)
{
    $today = new DateTime();
    $diff = $today->diff(new DateTime($birthday));

    if ($diff->y)
    {
        return 'Age: ' . $diff->y . ' years, ' . $diff->m . ' months';
    }
    elseif ($diff->m)
    {
        return 'Age: ' . $diff->m . ' months, ' . $diff->d . ' days';
    }
    else
    {
        return 'Age: ' . $diff->d . ' days old!';
    }
}; 

回归:

Age: 1 years, 2 months

可爱 - 对于只有几天的年轻人来说!