Skip to content

Instantly share code, notes, and snippets.

@joshualambert
Created December 20, 2012 17:47
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 joshualambert/4347159 to your computer and use it in GitHub Desktop.
Save joshualambert/4347159 to your computer and use it in GitHub Desktop.
time_since() - Time comparison function for PHP.
/*
* Originally written by: billythekid.
* https://twitter.com/billythekid
*
* Modified by: Joshua Lambert.
* https://twitter.com/zettageek
*
* Changelog:
* - Added array output.
* - Added ability to pass in custom end timestamp.
* - Added total_mins return to list of things returned.
*/
function time_since ($start, $end = time())
{
$diff = $end - $start;
$days = floor ( $diff/86400 ); //calculate the days
$diff = $diff - ($days*86400); // subtract the days
$hours = floor ( $diff/3600 ); // calculate the hours
$diff = $diff - ($hours*3600); // subtract the hours
$mins = floor ( $diff/60 ); // calculate the minutes
$diff = $diff - ($mins*60); // subtract the mins
$secs = $diff; // what's left is the seconds;
if ($secs!=0)
{
$secs .= " seconds";
if ($secs=="1 seconds") $secs = "1 second";
}
else $secs = '';
if ($mins!=0)
{
$mins .= " mins ";
if ($mins=="1 mins ") $mins = "1 min ";
$secs = '';
}
else $mins = '';
if ($hours!=0)
{
$hours .= " hours ";
if ($hours=="1 hours ") $hours = "1 hour ";
$secs = '';
}
else $hours = '';
if ($days!=0)
{
$days .= " days ";
if ($days=="1 days ") $days = "1 day ";
$mins = '';
$secs = '';
if ($days == "-1 days ") {
$days = $hours = $mins = '';
$secs = "less than 10 seconds";
}
}
else $days = '';
// return "$days $hours $mins $secs ago";
$days = preg_replace("[^0-9]", "", $days);
$hours = preg_replace("[^0-9]", "", $hours);
$mins = preg_replace("[^0-9]", "", $mins);
$secs = preg_replace("[^0-9]", "", $secs);
$days = str_replace(' ', '', $days);
$hours = str_replace(' ', '', $hours);
$mins = str_replace(' ', '', $mins);
$secs = str_replace(' ', '', $secs);
$total_mins = (($days * 24) / 60) +$mins;
$output['days'] = $days;
$output['hours'] = $hours;
$output['mins'] = $mins;
$output['secs'] = $secs;
$output['total_mins'] = $total_mins;
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment