How to convert timestamp to time ago in PHP

How to convert timestamp to time ago in PHP

This function will help to convert standard time into time "ago format".

Given a time and the task is to convert the timestamp to time ago. The time ago format removes the problem of different time zone conversions. Given below is a function to do the time conversions. In this function, taking the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format. To make this function, need to define some rules which determine the year, month, date, minutes etc from the remaining date after subtraction.

function time_ago($timestamp)
{
        $time_ago = strtotime($timestamp);
        $current_time = time();
        $time_difference = $current_time - $time_ago;
        $seconds = $time_difference;
        $minutes = round($seconds / 60);           // value 60 is seconds (60 sec in 1 min)
        $hours = round($seconds / 3600);           //value 3600 is 60 minutes * 60 sec
        $days = round($seconds / 86400);          //86400 = 24 * 60 * 60;
        $weeks = round($seconds / 604800);          // 7*24*60*60;
        $months = round($seconds / 2629440);     //((365+365+365+365+366)/5/12)*24*60*60
        $years = round($seconds / 31553280);     //(365+365+365+365+366)/5 * 24 * 60 * 60
        if ($seconds <= 60) {
            return "just_now";
        } else if ($minutes <= 60) {
            if ($minutes == 1) {
                return "1 " . "minute_ago";
            } else {
                return "$minutes " . "minutes_ago";
            }
        } else if ($hours <= 24) {
            if ($hours == 1) {
                return "1 " . "hour_ago";
            } else {
                return "$hours " . "hours_ago";
            }
        } else if ($days <= 30) {
            if ($days == 1) {
                return "1 " . "day_ago";
            } else {
                return "$days " ."days_ago";
            }
        } else if ($months <= 12) {
            if ($months == 1) {
                return "1 " ."month_ago";
            } else {
                return "$months " . "months_ago";
            }
        } else {
            if ($years == 1) {
                return "1 " ."year_ago";
            } else {
                return "$years " ."years_ago";
            }
        }
    }

print_r(time_ago('2022-07-07 07:50:09'));