CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a PHP snippet (http://www.codingforums.com/forumdisplay.php?f=41)
-   -   Function to retrieve remaining time from two timestamps (http://www.codingforums.com/showthread.php?t=246324)

BluePanther 12-14-2011 12:58 PM

Function to retrieve remaining time from two timestamps
 
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.

PHP Code:

function getRemaining($now,$future){
    if(
$future <= $now){
        
// Time has already elapsed
        
return FALSE;
    }
    else{
        
// 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.
PHP Code:

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


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


All times are GMT +1. The time now is 01:32 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.