PHP计算人的当前年龄

Jam*_*mes 7 php date

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

$person_date (string) = Day.Month.Year
Run Code Online (Sandbox Code Playgroud)

想要添加一个人的故乡.像" 目前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;
Run Code Online (Sandbox Code Playgroud)

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; }
Run Code Online (Sandbox Code Playgroud)

5)echo $ total_year;

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

谢谢.

Vol*_*erK 39

您可以使用DateTime类及其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);
Run Code Online (Sandbox Code Playgroud)

版画 29 years, 7 month, 20 days


Jon*_*han 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';
    }
}
Run Code Online (Sandbox Code Playgroud)