Posted By

natalie on 10/10/06


Tagged

time timesince


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

luman
millisami
breakerjump
joethermal


timesince function


 / Published in: PHP
 

  1. <?php
  2.  
  3. /* Works out the time since the entry post, takes a an argument in unix time (seconds) */
  4. function time_since($original) {
  5. // array of time period chunks
  6. $chunks = array(
  7. array(60 * 60 * 24 * 365 , 'year'),
  8. array(60 * 60 * 24 * 30 , 'month'),
  9. array(60 * 60 * 24 * 7, 'week'),
  10. array(60 * 60 * 24 , 'day'),
  11. array(60 * 60 , 'hour'),
  12. array(60 , 'minute'),
  13. );
  14.  
  15. $today = time(); /* Current unix time */
  16. $since = $today - $original;
  17.  
  18. // $j saves performing the count function each time around the loop
  19. for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  20.  
  21. $seconds = $chunks[$i][0];
  22. $name = $chunks[$i][1];
  23.  
  24. // finding the biggest chunk (if the chunk fits, break)
  25. if (($count = floor($since / $seconds)) != 0) {
  26. // DEBUG print "<!-- It's $name -->\n";
  27. break;
  28. }
  29. }
  30.  
  31. $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  32.  
  33. if ($i + 1 < $j) {
  34. // now getting the second item
  35. $seconds2 = $chunks[$i + 1][0];
  36. $name2 = $chunks[$i + 1][1];
  37.  
  38. // add second item if it's greater than 0
  39. if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
  40. $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
  41. }
  42. }
  43. return $print;
  44. }
  45.  
  46. ?>

Report this snippet  

You need to login to post a comment.