Skip to content

Instantly share code, notes, and snippets.

@ryanmr
Created September 6, 2013 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmr/6460047 to your computer and use it in GitHub Desktop.
Save ryanmr/6460047 to your computer and use it in GitHub Desktop.
Original human_time_difference function; given a timestamp and optionally another, it will return the largest reasonable time differential between the two.
public static function human_time_difference($from, $to = '') {
if ( empty($to) ) {
$to = time();
}
$periods = array(
'minutes' => array('%s minute', '%s minutes'),
'hours' => array('%s hour', '%s hours'),
'days' => array('%s day', '%s days'),
'weeks' => array('%s week', '%s weeks'),
'months' => array('%s month', '%s months'),
'years' => array('%s year', '%s years')
);
$ranges = array(
'years' => 31556926,
'months' => 2592000,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60
);
$diff = (int) abs($to - $from);
$since = '';
foreach ($ranges as $unit => $value) {
if ( $diff <= $value ) continue;
$time = round($diff / $value);
if ( $time < 1 ) {
$time = 1;
}
$since = sprintf(_n($periods[$unit][0], $periods[$unit][1], $time), $time);
break;
}
return $since;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment