View Full Version : Function to retrieve remaining time from two timestamps

12-14-2011, 12:58 PM
After answering this post - http://www.codingforums.com/showthread.php?t=246280 - I thought it would be useful to a lot of people if I expanded the function a bit and posted it here.

function getRemaining($now,$future){
if($future <= $now){
// Time has already elapsed
return FALSE;
// Get difference between times
$time = $future - $now;
$minutesFloat = $time/60;
$minutes = floor($minutesFloat);
$hoursFloat = $minutes/60;
$hours = floor($hoursFloat);
$daysFloat = $hours/24;
$days = floor($daysFloat);
return array(
'days' => $days,
'hours' => round(($daysFloat-$days)*24),
'minutes' => round(($hoursFloat-$hours)*60),
'seconds' => round(($minutesFloat-$minutes)*60)

This function returns the difference between two timestamps, separated into an array with indexes days, hours, minutes and seconds. For practical reasons, it will return FALSE if the time to be compared with $now is less than (or equal to) $now.

For example, if you had a list of items in an auction and the database held a timestamp for when the auction ends, you would enter this timestamp as the second parameter to the function, and time() as the first parameter. Then, when the auction end timestamp is <= time(), the function returns false.

$result = getRemaining(time(),$auctionEnd);
echo 'Auction has ended!';
// do what you want with $result array

Hope it's useful, and all feedback welcomed :)