public
Created

time_since() - Time comparison function for PHP.

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/*
* 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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.