2010-08-01 112 views
6

我在我的网站上的格式为12.01.1980的出生日期。PHP计算人的当前年龄

$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)回声$ total_year;

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

谢谢。

+0

计算出生日期到现在的天数乘以4除以1461(而不是浮动除数365.25)? – pascal 2010-08-01 06:30:59

+0

它会给出正确答案吗? – James 2010-08-01 06:34:33

+0

@pascal:你如何计算日子? – Svish 2010-11-30 11:42:06

回答

36

您可以使用及其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

这就是我需要的,谢谢你! – James 2010-08-01 06:49:42

+0

这真的很有帮助,谢谢! – itsricky 2013-02-09 08:52:21

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'; 
    } 
} 
+1

这里的工作很好@jonathan。它是VolkerK工作的一个真正常识性的延伸。我再次修改它以提供更多的“人类”读数,请参见下文。谢谢! – itsricky 2013-02-09 08:53:44

2

我已经进一步扩展了@乔纳森的答案,以提供更“人性化”的回应。

使用这些日期:

$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 

可爱 - 真是为年轻的只有几天老了!

+0

$生日应该是$ bday – ow3n 2015-03-11 20:50:47