Posted By

mattkenefick on 05/20/08


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

xuanyan
silentbob84


PHP: TimeFromNow


 / Published in: PHP
 

  1. function timeFromNow($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
  2. $now = timezone_makeDate('',time());
  3.  
  4. #If the difference is positive "ago" - negative "away"
  5. ($timestamp >= $now) ? $action = 'away' : $action = 'ago';
  6.  
  7. # Set the periods of time
  8. $periods = array( "m", "h", "d", "w", "mon", "y");
  9. $lengths = array( 60, 3600, 86400, 604800, 2630880, 31570560);
  10.  
  11. $diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
  12.  
  13. $prec_key = array_search($precision_level,$periods);
  14.  
  15. # round diff to the precision_level
  16. $diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];
  17.  
  18. # if the diff is very small, display for ex "just seconds ago"
  19. if ($diff <= 10) {
  20. $periodago = max(0,$prec_key-1);
  21. $agotxt = $periods[$periodago];
  22. return "just $agotxt $action";
  23. }
  24.  
  25. # Go from decades backwards to seconds
  26. $time = "";
  27. for ($i = (sizeof($lengths) - 1); $i>=1; $i--) {
  28. if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) { # if the difference is greater than the length we are checking... continue
  29. $val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
  30. $time .= $val ."". $periods[$i-1].($val > 1 ? ' ' : ' '); # The value, then the name associated, then add 's' if plural
  31. $diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
  32. if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
  33. $max_detail_levels--;
  34. }
  35. }
  36.  
  37.  
  38. # Basic error checking.
  39. if($time == "") {
  40. return "Unable to calculate time";
  41. } else {
  42. return $time.$action;
  43. }
  44.  
  45. }

Report this snippet  

You need to login to post a comment.