Last Updated: June 11, 2021
·
805
· u01jmg3

From a timestamp return the relative time such as '4 weeks ago'

<?php
    function getRelativeTime($timestamp) {
        $difference = strtotime(date('Y-m-d H:i:s')) - strtotime($timestamp);
        $periods    = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
        $lengths    = [60, 60, 24, 7, 4.35, 12, 10]; 

        // This was in the past
        if ($difference >= 0) {
            $ending = 'ago';
        // This was in the future
        } else if ($difference < 0) {
            $difference = -$difference;
            $ending = 'to go';
        }

        $j = 0;
        while ($difference >= $lengths[$j] && $j < count($lengths)) {
            $difference /= $lengths[$j];
            $j++;
        }

        $difference = round($difference);

        if ($difference != 1) {
            $periods[$j] .= 's';
        }

        $text = "$difference $periods[$j] $ending";

        return $text;
    }