Skip to content

Instantly share code, notes, and snippets.

@jamescarlos
Created June 4, 2009 09:41
Show Gist options
  • Save jamescarlos/123540 to your computer and use it in GitHub Desktop.
Save jamescarlos/123540 to your computer and use it in GitHub Desktop.
formats a datetime (yyyy-mm-dd hh:mm:ss) into a human readable elapsed format
/**
* formats a datetime (yyyy-mm-dd hh:mm:ss) into a human readable elapsed format
*
* @return string
* @param string datetime
* @param string word that will end the string
* @param int maximum value before returning the datetime in the datetime_format
* @param string max unit to use
* @param string datetime format
*/
function format_time_elapsed($datetime, $end_word = 'ago', $max_value = '', $max_unit = 'years', $datetime_format = 'm/d/Y')
{
$time = strtotime($datetime);
$diff = time() - $time;
$units = array();
$units[] = array('unit' => 'seconds', 'value' => 1);
$units[] = array('unit' => 'minutes', 'value' => 60);
$units[] = array('unit' => 'hours', 'value' => 60 * 60);
$units[] = array('unit' => 'days', 'value' => 60 * 60 * 24);
$units[] = array('unit' => 'weeks', 'value' => 60 * 60 * 24 * 7);
$units[] = array('unit' => 'months', 'value' => 60 * 60 * 24 * 30);
$units[] = array('unit' => 'years', 'value' => 60 * 60 * 24 * 365);
$return_unit = '';
$return_value = '';
foreach ($units as $key => $value)
{
if ($diff > $value['value'] and isset($units[$key + 1]) and $diff > $units[$key + 1]['value'] and $value['unit'] != $max_unit)
{
continue;
}
else
{
$return_value = round($diff / $value['value']);
$return_unit = $value['unit'];
if ($return_value == 1)
{
$return_unit = rtrim($return_unit, 's');
}
break;
}
}
if ($max_value and $return_value > $max_value)
{
return format_datetime($datetime, $datetime_format);
}
else
{
return $return_value . ' ' . $return_unit . ' ' . $end_word;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment