8wcmla
Last Updated: February 20, 2017
·
704
· u01jmg3

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

php
<?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;
    }

1 Response
Add your response

694

Super useful function. Been using something similar but a bit less clean my self.

over 1 year ago ·