Geekpedia Programming Tutorials






Display Time Left To a Date

A PHP function to display the time between now and a future date supplied as Unix time, in human readable format, using two blocks of time periods (year, month, week, day, hour or minute.)

On Friday, July 31st 2009 at 09:30 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.7 with 3 votes)
Contextual Ads
More PHP Resources
Advertisement
  1. function TimeTo($future) // $original should be the future date and time in unix format
  2. {
  3.     // Common time periods as an array of arrays
  4.     $periods = array(
  5.         array(60 * 60 * 24 * 365 , 'year'),
  6.         array(60 * 60 * 24 * 30 , 'month'),
  7.         array(60 * 60 * 24 * 7, 'week'),
  8.         array(60 * 60 * 24 , 'day'),
  9.         array(60 * 60 , 'hour'),
  10.         array(60 , 'minute'),
  11.     );
  12.    
  13.     $today = time();
  14.     $since = $future - $today; // Find the difference of time between now and the future
  15.    
  16.     // Loop around the periods, starting with the biggest
  17.     for ($i = 0, $j = count($periods); $i < $j; $i++)
  18.         {
  19.         $seconds = $periods[$i][0];
  20.         $name = $periods[$i][1];
  21.        
  22.         // Find the biggest whole period
  23.         if (($count = floor($since / $seconds)) != 0)
  24.                 {
  25.             break;
  26.         }
  27.     }
  28.    
  29.     $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  30.    
  31.     if ($i + 1 < $j)
  32.         {
  33.         // Retrieving the second relevant period
  34.         $seconds2 = $periods[$i + 1][0];
  35.         $name2 = $periods[$i + 1][1];
  36.        
  37.         // Only show it if it's greater than 0
  38.         if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0)
  39.                 {
  40.             $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
  41.         }
  42.     }
  43.     return $print;
  44. }
  45.  
  46. echo TimeTo(1359101056);
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this code snippet
Comment Current Comments
There are no comments.

Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Source Code
There is no related code.

Comment Related Tutorials
There are no related tutorials.

Jobs PHP Job Search
My skills include:

Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons