计算年龄和月份

时间:2017-11-09 09:30:06

标签: php date

我有一个计算年龄的代码,但我需要对此进行一些修改:

<?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岁,我需要显示月数。因此,如果生日是2016年11月9日,它必须显示12个月,如果月数高于23,则显示年龄。

有人可以帮我这个吗?

此致 罗伯特

1 个答案:

答案 0 :(得分: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