d
Amit DhamuSoftware Engineer
 

Time Ago Function

3 minute read 00000 views

Method 1

// Takes a time() value. If necessary, use time_ago(strtotime(the_time))
function time_ago($time) {
    $gap = time() - $time;

    if ($gap < 5) {
        return 'less than 5 seconds ago';
    } else if ($gap < 10) {
        return 'less than 10 seconds ago';
    } else if ($gap < 20) {
        return 'less than 20 seconds ago';
    } else if ($gap < 40) {
        return 'half a minute ago';
    } else if ($gap < 60) {
        return 'less than a minute ago';
    }

    $gap = round($gap / 60);

    if ($gap < 60)  {
        return $gap . ' minute' . ($gap < 1 ? 's' : '') . ' ago';
    }

    $gap = round($gap / 60);

    if ($gap < 24)  {
        return 'about ' . $gap . ' hour' . ($gap < 1 ? 's' : '') . ' ago';
    }

    return date('j M', $time);
}

Method 2

function ElapsedTime($time) {
    $periods = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
    $lengths = ['60', '60', '24', '7', '4.35', '12', '10'];
    $now = time();
    $difference = $now - $time;
    $tense = 'ago';

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

    $difference = round($difference);

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