2010-08-01 177 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