Useful PHP utility function that will display a time as “1 year, 1 week ago” or “5 minutes, 7 seconds ago”, etc…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * @desc Display a time as "1 year, 1 week ago" or "5 minutes, 7 seconds ago", etc... * @param string $date - A date/time string. * @param int $granularity * @param string $before - Text to display before, eg 'Posted', 'Delivered' ect * @return string, descriptive time ago text. e.g. 'Posted 3 months 2 weeks ago' */ function timeAgo($date, $granularity = 2, $before = '') { $retval = ''; $date = strtotime($date); $difference = time() - $date; $periods = [ 'decade' => 315360000, 'year' => 31536000, 'month' => 2628000, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1 ]; if ($difference < 50) { // less than 50 seconds ago, let's say "just now" $retval = $before . ' Just now'; return $retval; } else { foreach ($periods as $key => $value) { if ($difference >= $value) { $time = floor($difference / $value); $difference %= $value; $retval .= ($retval ? ' ' : '') . $time . ' '; $retval .= (($time > 1) ? $key . 's' : $key); $granularity--; } if ($granularity == '0') { break; } } return "$before $retval ago"; } } |