PHP calculate person's current age

后端 未结 3 1199
野性不改
野性不改 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: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';
        }
    }
    

提交回复
热议问题