Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-14-2011, 12:58 PM   PM User | #1
BluePanther
Senior Coder

 
Join Date: Jul 2011
Posts: 1,226
Thanks: 3
Thanked 171 Times in 171 Posts
BluePanther is on a distinguished road
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
BluePanther is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:22 AM.


Advertisement
Log in to turn off these ads.