Skip to content

Instantly share code, notes, and snippets.

@ryanmr

ryanmr/utility.php

Created Sep 6, 2013
Embed
What would you like to do?
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
You can’t perform that action at this time.