Skip to content

Instantly share code, notes, and snippets.

@rattrap
Created December 4, 2014 21:51
Show Gist options
  • Save rattrap/e4f0239f2efb8301d6d0 to your computer and use it in GitHub Desktop.
Save rattrap/e4f0239f2efb8301d6d0 to your computer and use it in GitHub Desktop.
Time ago in PHP
<?php
function time_ago($time) {
$time = time() - $time;
if($time < 5) {
return 'Just now';
}
$units = array(
365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$units_plural = array(
'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach($units as $seconds => $unit) {
$decimal = $time / $seconds;
if($decimal >= 1) {
$rounded = round($decimal);
$plural = $rounded > 1;
return $rounded . ' ' . ($plural ? $units_plural[$unit] : $unit) . ' ago';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment