Posted By

uberdragon on 03/17/11


Tagged

countDown


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

uberdragon


Function to return amount of time between two unix time stamps as it would be verbalized.


 / Published in: PHP
 

Display amount of time distance between two timestamps in the 2 largest possible time frame terms, adding plural when appropriate. If the second parameter for ending time stamp is left blank the current time() is used.

usage: echo timeSince(1300000006,1300162842); // will echo 1 day, 21 hours and echo timeSince(1300162702,1300162842); // will echo 2 minutes, 20 seconds

The last parameter is the number of time units to display (ie: 2 might display minutes, seconds while 3 will display hours, minutes seconds). This defaults to 2.

  1. function timeSince($start,$end='',$units=2) { // $start and $end should be Unix time() 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. array(1 , 'second'),
  12. );
  13.  
  14. $end = (!empty($end))?$end:time(); // if no end timestamp given use the current one for end date
  15. $since = $end - $start; // Find the difference of time between now and the past
  16. // $end and $start input could be swapped in order to find the time 'until' ;)
  17. // Loop around the periods, starting with the biggest
  18. for ($i = 0, $j = count($periods); $i < $j; $i++){
  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. break;
  25. }
  26. }
  27.  
  28. $output = ($count == 1) ? '1 '.$name : "$count {$name}s";
  29. $deducted = ($seconds * $count);
  30.  
  31. for($z = 1, $j = count($periods); $z < $j; $z++) {
  32. if ($units > $z && $i + $z < $j){
  33. // Retrieving the next requested relevant period
  34. $seconds = $periods[$i + $z][0];
  35. $name = $periods[$i + $z][1];
  36.  
  37. // Only show it if it's greater than 0
  38. if (($count = floor(($since - $deducted) / $seconds)) != 0){
  39. $deducted = $deducted+($seconds * $count);
  40. $output .= ($count == 1) ? ', 1 '.$name : ", {$count} {$name}s";
  41. }
  42. }
  43. }
  44.  
  45. return $output;
  46. }

Report this snippet  

You need to login to post a comment.