Skip to content

Instantly share code, notes, and snippets.

@etaubman
Forked from danoc/time_since.php
Last active December 17, 2015 12:29
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 etaubman/5609636 to your computer and use it in GitHub Desktop.
Save etaubman/5609636 to your computer and use it in GitHub Desktop.
<?php
/**
* Return a "human-readable" time such as 8 hours ago.
*
* @author Dan O'Connor, Modified by Ethan Taubman
*
* @param string $time such as: 2013-03-18 21:13:59
* @param string $format optional such as: "<em>%d</em> %s%s since last post."
*
* @return string
*/
function time_since($time, $format = "%d %s%s")
{
$date = new \DateTime;
$date->setTimestamp(strtotime($time));
$interval = $date->diff(new \DateTime('now'));
$measures = array(
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second'
);
foreach ($measures as $k => $v) {
$digit = $interval->{$k};
if ($digit !== 0) {
return sprintf($format,$digit,$v,($digit > 1 ? 's' : ''));
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment