Posted By

browncardigan on 02/25/10


Tagged

time


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

dantreacy


getTimeDiff


 / Published in: PHP
 

  1. function getTimeDiff($timestamp=false, $loop=false) {
  2.  
  3. $current_time = time();
  4.  
  5. if ($timestamp) {
  6.  
  7. // Determine the difference, between the time now and the timestamp
  8. $difference = $current_time - $timestamp;
  9.  
  10. // Set the periods of time
  11. $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
  12. $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
  13.  
  14. // Determine which period we should use, based on the number of seconds lapsed.
  15. // If the difference divided by the seconds is more than 1, we use that.
  16. // Eg 1 year / 1 decade = 0.1, so we move on
  17. // Go from decades backwards to seconds
  18. for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $difference / $lengths[$val]) <= 1); $val--);
  19.  
  20. // Ensure the script has found a match
  21. if ($val < 0) $val = 0;
  22.  
  23. // Determine the minor value, to recurse through
  24. $new_time = $current_time - ($difference % $lengths[$val]);
  25.  
  26. // Set the current value to be floored
  27. $number = floor($number);
  28.  
  29. // If required create a plural
  30. if($number != 1) $periods[$val].= "s";
  31.  
  32. // Return text
  33. $text = sprintf("%d %s ", $number, $periods[$val]);
  34.  
  35. // Ensure there is still something to recurse through, and we have not found 1 minute and 0 seconds.
  36. // note: 'the loop' is turned off - it will only show the highest
  37. if ($loop && ($val >= 1) && (($current_time - $new_time) > 0)){
  38. $text .= getTimeDiff($new_time);
  39. }
  40.  
  41. return $text;
  42. }
  43. }

Report this snippet  

You need to login to post a comment.