2017-11-09 37 views
0

私は年齢を計算しますが、私はこの1つ上のいくつかの変更を必要とするコードを持っている:計算年齢と月

<?php 
    //date in mm/dd/yyyy format; or it can be in other formats as well 
    $birthDate = $tk_image_geboortedag ."-". $tk_image_geboortemaand ."-". $tk_image_geboortejaar; 
    //explode the date to get month, day and year 
    $birthDate = explode("-", $birthDate); 
    //get age from date or birthdate 
    $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") 
     ? ((date("Y") - $birthDate[2]) - 1) 
     : (date("Y") - $birthDate[2])); 
     echo "Huidige leeftijd: " . $age; 
?> 

今では返しますHuidigeはleeftijd:19(それは計算何でも)。

必要は何ですか。年齢が2歳未満の場合は、月額を表示する必要があります。したがって、生年月日が09-11-2016であれば、12ヶ月を表示しなければならず、月の数が23を上回る場合は年齢を表示します。

誰かがこれを手伝ってくれますか?

よろしく、 ロバート

答えて

2

あなたはPHP DateTime objectを使用したいです。 this topic from Paulund読む:

// $birthDate = $tk_image_geboortedag ."-". $tk_image_geboortemaand ."-". $tk_image_geboortejaar; 

// The birth date as a DateTime Object 
// format typically YYYY/MM/DD 
// timezone field is optional, shown here simply as illustration. 
$date1 = new DateTime($tk_image_geboortejaar."-". $tk_image_geboortemaand ."-". $tk_image_geboortedag 
      , new DateTimeZone('Europe/Amsterdam')); 

// The date now as a DateTime Object. 
$date2 = new DateTime(); 

$difference = $date1->diff($date2); 

この意志出力二つの日付の違いを、あなたを示してどのように多くの年、月と日、DateInterval objectで復帰。

またDateIntervalオブジェクトが保持している値がものを見ることができます。

だから、
print_r($difference); 

/*** 
    [y] => 3 
    [m] => 5 
    [d] => 15 
    [h] => 0 
    [i] => 0 
    [s] => 0 
    [weekday] => 0 
    [weekday_behavior] => 0 
    [first_last_day_of] => 0 
    [invert] => 0 
    [days] => 1264 
    [special_type] => 0 
    [special_amount] => 0 
    [have_weekday_relative] => 0 
    [have_special_relative] => 0 
***/ 

を、バックのコードに:

/*** Output Years ***/ 
$age = $difference->y." jaar"; 

if($difference->m < 24){ 
    /*** Output months ***/ 
    $age = $difference->m." maanden"; 
} 

echo "Huidige leeftijd: " . $age; 

this very similar question and its excellent answersを参照してください。

+0

'$ tk_image_geboortedag"ではなく、 'explode'を使う理由は - "です。 $ tk_image_geboortemaand。 " - " $ tk_image_geboortejaar; 'ヴァルス?ただ注文を変更してください... – HtmHell

+0

あなたの答えをありがとう、完璧に説明した:)私はただ一つ変更した、私はif($ difference-> m <24){if($ difference-> y <2){。したがって、yの数が2以下の場合はmを表示します。それとも私は何かが恋しい? – n00bly

+1

@ n00blyいいえ、彼らは同じことです。同じしきい値の同じ値をチェックするさまざまな方法。あなたのお手伝いをしてうれしいです: – Martin

関連する問題