Helpful Time Format Functions
I have a couple functions that I use to make human friendly time formats with PHP. The first one is fairly straight forward:
function human_time_format($datetime)
{
return date('F j, Y @ g:i a', strtotime($datetime));
}
Example result:
March 6, 2012 @ 1:50 am
The next function is a bit more complex, and generates a relative time format:
function relative_time_format($datetime)
{
$difference = time() - strtotime($datetime);
$periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
$lengths = array(60, 60, 24, 7, 4.35, 12, 10);
// This was in the past.
if ($difference > 0)
{
$ending = 'ago';
}
// This is in the future.
else
{
$difference = -$difference;
$ending = 'from now';
}
for ($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if ($difference != 1)
$periods[$j] .= 's';
return $difference . ' ' . $periods[$j] . ' ' . $ending;
}
Example result:
1 minute ago