简体   繁体   中英

Calculate age and months

I have a code which calculates the age but I need some modification on this one:

<?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;
?>

Now it returns: Huidige leeftijd: 19 (whatever it calculates).

What is need is; If the age is below 2 years I need to display the amount of months. So if the birthdate is 09-11-2016 it must show 12 months and if the amount of months is higher then 23 then show the age in years.

Can someone help me with this?

Regards, Robert

You want to use the PHP DateTime object . Read 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);

This will output the difference in the two dates and show you how many years, months and days, return in a DateInterval object .

You can also see what values the DateInterval object holds:

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
***/

So, back to the code:

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

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

echo "Huidige leeftijd: " . $age;

Also please see this very similar question and its excellent answers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM