Skip to content

Instantly share code, notes, and snippets.

@rowanmanning
Created February 11, 2011 12:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rowanmanning/822283 to your computer and use it in GitHub Desktop.
Save rowanmanning/822283 to your computer and use it in GitHub Desktop.
Calculate the amount of time between two dates/timestamps in PHP. Return the result as a nicely formatted string or an array of data.
<?php
/**
* Get the relative time between two timestamps.
*
* @access public
* @param integer|string $time The date or timestamp that represents the time we're comparing to.
* @param integer|string $comparison_time [optional] The date or timestamp we want comparisons to be relative to. Defaults to the current timestamp.
* @param boolean $return_array [optional] Whether to return the relative time as an array of components rather than a string. Default value is FALSE.
* @return string Returns the amount of time between the two timestamps as a string or an array if $return_array is TRUE.
*/
function relative_time($time, $comparison_time = null, $return_array = false) {
// static data
static $time_units = array(
'year' => 31536000,
'month' => 2678400,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
// sanitize arguments
$time = (is_string($time) ? strtotime($time) : (integer) $time);
$comparison_time = ($comparison_time === null ? time() : (is_string($comparison_time) ? strtotime($comparison_time) : (integer) $comparison_time));
$return_array = (boolean) $return_array;
// get time difference
$time_difference = $time - $comparison_time;
$time_difference_positive = abs($time_difference);
// get the prefix/suffix
$time_prefix = '';
$time_suffix = '';
if ($time_difference < 0) {
$time_suffix = 'ago';
}
else if ($time_difference > 0) {
$time_prefix = 'in';
}
// get the unit
$time_unit = 'second';
$unit_time_difference = $time_difference_positive;
foreach ($time_units as $unit => $unit_seconds) {
if ($time_difference_positive >= $unit_seconds) {
$unit_time_difference = round($time_difference_positive / $unit_seconds);
$time_unit = $unit;
break;
}
}
// pluralise unit
if ($unit_time_difference > 1) {
$time_unit .= 's';
}
// return
if ($return_array) {
// return relative time as an array
$relative_time = array(
'offset' => $unit_time_difference,
'offset_seconds' => $time_difference_positive,
'unit' => $time_unit,
'unit_plural' => ($unit_time_difference > 1),
'prefix' => $time_prefix,
'suffix' => $time_suffix
);
return $relative_time;
}
else {
// return relative time as a string
$relative_time = ($time_prefix ? $time_prefix . ' ' : '') . $unit_time_difference . ' ' . $time_unit . ($time_suffix ? ' ' . $time_suffix : '');
return ($time_difference == 0 ? 'just now' : $relative_time);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment