Tell me, how can you find out how old the user is if he entered only the date of birth, but not a number indicating the age? Has anyone encountered this problem? Tell me, please, how this can be implemented, if possible, give an example. Thank you in advance!

    3 answers 3

    $birthday = '1985-04-15'; //Дата рождения $age = floor( ( time() - strtotime($birthday) ) / (60 * 60 * 24 * 365.25) ); //Формула echo $age; //27 
    • one
      I checked and did not understand. It seems to be correct, but: $birthday = '1985-08-30'; //Дата рождения $age = round( ( time() - strtotime($birthday) ) / (60 * 60 * 24 * 365.25) ); //Формула echo $age; //27 $birthday = '1985-08-30'; //Дата рождения $age = round( ( time() - strtotime($birthday) ) / (60 * 60 * 24 * 365.25) ); //Формула echo $age; //27 $birthday = '1985-08-30'; //Дата рождения $age = round( ( time() - strtotime($birthday) ) / (60 * 60 * 24 * 365.25) ); //Формула echo $age; //27 Why 27? After all, 27 will be only 30.08 - Dem
    • one
      Yes you are right. Still floor (). - Indifferent
    • Divide by 365.25 is a rough receipt of the date of birth, there will be an error of a few days. Gave the answer how to get for sure. - Goncharov Alexander

    This task can also be performed using the PHP function date_diff or DateTime :: diff , which is basically the same thing. DateTime :: diff - date_diff - Returns the difference between two DateTime objects . This task can also be solved using the MySQL DATEDIFF () function.

      The functional style is the age determination in years at the time point $ ageTime:

       function getAge($birthdate, $ageTime = null/*now by default*/){ return (new DateTime()) ->setTimestamp($ageTime ? $ageTime : time()) ->diff(new DateTime($birthdate))->format('%Y'); }