2009-07-11 30 views
12

日付から年:0000-00-00を計算する関数を探しています。 この関数が見つかりましたが、動作しません。日付を年から計算する

// Calculate the age from a given birth date 
// Example: GetAge("1986-06-18"); 
function getAge($Birthdate) 
{ 
    // Explode the date into meaningful variables 
    list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate); 
    // Find the differences 
    $YearDiff = date("Y") - $BirthYear; 
    $MonthDiff = date("m") - $BirthMonth; 
    $DayDiff = date("d") - $BirthDay; 
    // If the birthday has not occured this year 
    if ($DayDiff < 0 || $MonthDiff < 0) 
    $YearDiff--; 
} 

echo getAge('1990-04-04'); 

出力は何も:/
私はエラーの報告をしましたが、私はあなたが$ yearDiffを返却する必要があるすべてのエラー

+0

この関数には 'return'ラインを持っていない計算します。非常に不完全なように見えます。 – deceze

答えて

29

関数が何も返さないため、コードが機能しません。限りアルゴリズムが行くように、これはどう

function getAge($then) { 
    $then_ts = strtotime($then); 
    $then_year = date('Y', $then_ts); 
    $age = date('Y') - $then_year; 
    if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--; 
    return $age; 
} 
print getAge('1990-04-04'); // 19 
print getAge('1990-08-04'); // 18, birthday hasn't happened yet 

これが受け入れ答えin this questionとして(単にPHPで)同じアルゴリズムです。

それを行うための簡単な方法:

function getAge($then) { 
    $then = date('Ymd', strtotime($then)); 
    $diff = date('Ymd') - $then; 
    return substr($diff, 0, -4); 
} 
+0

甘い! –

+0

あなたはさらに進んで数年の小数点を解くことができます... – jsnfwlr

+0

それを行う第2の方法では、入力$を変更するべきではありません。これを別の変数として保存する必要があります。 – hawaiianchimp

2

を得るいけない、私は思います。

6

これを行うための別の方法はであるPHP 5.2のように、新しいあるPHPのDateTime class

$birthdate = new DateTime("1986-06-18"); 
$today  = new DateTime(); 
$interval = $today->diff($birthdate); 
echo $interval->format('%y years'); 

See it in action

+0

小規模の訂正:DateTime :: diff()はPHP 5.3以降では新しい – turibe

1

シングルここで働くことができます

function calculateAge($dob) { 
    return floor((time() - strtotime($dob))/31556926); 
} 

は、したがって、それは何も出力しない、年齢

$age = calculateAge('1990-07-10');