Posted By

browncardigan on 02/08/10


Tagged


Versions (?)

getTimeDiff


 / Published in: PHP
 

URL: http://bettesmidler.com/code/2009-08-11.htm

  1. function getTimeDiff($timestamp=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. // Go from decades backwards to seconds
  17. for (
  18. $val = sizeof($lengths) - 1;
  19. ($val >= 0) && (($number = $difference / $lengths[$val]) <= 1);
  20. $val--
  21. );
  22.  
  23. // Ensure the script has found a match
  24. if ($val < 0) $val = 0;
  25.  
  26. // Determine the minor value, to recurse through
  27. $new_time = $current_time - ($difference % $lengths[$val]);
  28.  
  29. // Set the current value to be floored
  30. $number = floor($number);
  31.  
  32. // If required create a plural
  33. if ($number != 1) $periods[$val] .= "s";
  34.  
  35. // Return text
  36. $text = sprintf("%d %s ", $number, $periods[$val]);
  37.  
  38. return $text;
  39. }
  40. }

Report this snippet  

You need to login to post a comment.