PHP calculate person's current age

后端 未结 3 1193
野性不改
野性不改 2020-12-09 22:07

I have birth dates on my site in format 12.01.1980.

$person_date (string) = Day.Month.Year

Want to add an oldness of the perso

相关标签:
3条回答
  • 2020-12-09 22:41

    I've further extended @Jonathan's answer, to give a more 'human-friendly' response.

    Using these dates:

    $birthday= new DateTime('2011-11-21');
    //Your date of birth.
    

    And calling this function:

    function calculate_age($birthday)
    {
        $today = new DateTime();
        $diff = $today->diff(new DateTime($birthday));
    
        if ($diff->y)
        {
            return 'Age: ' . $diff->y . ' years, ' . $diff->m . ' months';
        }
        elseif ($diff->m)
        {
            return 'Age: ' . $diff->m . ' months, ' . $diff->d . ' days';
        }
        else
        {
            return 'Age: ' . $diff->d . ' days old!';
        }
    }; 
    

    Is returning:

    Age: 1 years, 2 months
    

    Cute - for really young ones only a few days old!

    0 讨论(0)
  • 2020-12-09 22:45

    You can use the DateTime class and its diff() method.

    <?php
    $bday = new DateTime('12.12.1980');
    // $today = new DateTime('00:00:00'); - use this for the current date
    $today = new DateTime('2010-08-01 00:00:00'); // for testing purposes
    
    $diff = $today->diff($bday);
    
    printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
    

    prints 29 years, 7 month, 20 days

    0 讨论(0)
  • 2020-12-09 22:47

    An extension of @VolkerK's answer - which is excellent! I never like seeing the age of zero, which happens if you only use the year. This function shows their age in months (if they are one month old or more), and otherwise in days.

    function calculate_age($birthday)
    {
        $today = new DateTime();
        $diff = $today->diff(new DateTime($birthday));
    
        if ($diff->y)
        {
            return $diff->y . ' years';
        }
        elseif ($diff->m)
        {
            return $diff->m . ' months';
        }
        else
        {
            return $diff->d . ' days';
        }
    }
    
    0 讨论(0)
提交回复
热议问题